Rewrite Query String to Path with htaccess

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!

Share on Twitter | Discuss on Twitter | Edit on Github ✏️

Stay in touch

Like the posts you see here? Sign up to get notified about new ones.