Tania Rascia

Skip Navigation
Rewrite Query String to Path with htaccess

Rewrite Query String to Path with htaccess

 /  4 responses

Let’s say I have this URL:

http://example.com/users.php?name=tania

And I want this URL:

http://example.com/users/tania

I can do so with the following .htaccess:

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?users/(.*?)/?$ /users.php?name=$1 [L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /users\.php\?name=([^\&\ ]+)
RewriteRule ^/?users\.php$ /users/%1? [L,R=301]

I can even still GET the URL query.

users.php
<?php

echo $_SERVER['REQUEST_URI'] . '<br>';

print_r($_GET);
/users/tania Array ( [name] => tania )

Alternatively, you could redirect everything to index.php and route it that way.

RewriteEngine On
RewriteRule ^([a-zA-Z0-9]+)$ index.php?url=$1

That’s all!

Newsletter

Get updated when I create new content.
Unsubscribe whenever. Never any spam.

Note

I'm Tania. I turn down every ad, affiliate, and sponsor request I get. I write free resources that help thousands of people successfully become devs. If you enjoy my content, please consider supporting what I do.

Support my work

Write a response

Your email address will not be published. Required fields are marked *

All code will be displayed literally.

Discussion