How to Rewrite Query String to Path with htaccess

Published: Nov 23, 2020 - Updated: Mar 16, 2022

In this short article, I’m going to share how to rewrite query string to path with htaccess. Let’s see:

Problem

Let’s take a link:

http://example.dev/users.php?username=obydul

We want to make this URL like:

http://example.dev/obydul

Solution

We can do it easily with .htaccess. Have a look at the solution:

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

We’re done. We can still get the parameter vaule like:

$username = $_GET['username'];

If we want to make like:

http://example.dev/user/obydul

Paste this code in the .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?user/(.*?)/?$ /?username=$1 [L]
That’s it. Thanks for reading. ?