How to Rewrite Query String to Path with htaccess

Published on November 23, 2020 25 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

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. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

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