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!

Note

Hi, my name is Tania Rascia. I've turned down every offer for advertisements or sponsored posts on this website. I write free resources that have helped thousands of people successfully transition into a web development career.

My committment is to no bullshit, no sponsored posts, no ads, and no paywalls. If you enjoy my content, please consider supporting what I do.

Support my work

Newsletter

New articles on web development every two weeks.

Write a response

Your email address will not be published.

All code will be displayed literally.

Discussion