How to Rewrite Query String to Path with htaccess

Rewrite Query String to Path with htaccess – In general, using Apache’s .htaccess to redirect URLs is simple. The only trick is to redirect based on the query string value of the URL. Because doing so necessitates somewhat different instructions that many users are unaware of, questions like “why isn’t my redirect working for query strings?” are typical. You may need to redirect a URL that includes a query string on occasion. In order for the redirect rule to correctly deliver your readers to the right page, you’ll need to employ the RewriteEngine. To build a redirect rewrite rule for a specific page, follow the steps in the tutorial below. A query string will be used for the redirect.

Let’s say I have this URL: The query string is defined as anything following the first question mark,?

It’s worth noting that query strings can have both a key and a value. To Apache, it makes no difference since the entire query string – whatever it is — is treated as a single string. To put it another way, Apache doesn’t distinguish between keys and values; the query string is just whatever follows the initial question mark in the URL. When it comes to redirecting based on query strings, this makes things a lot easier.

And I want to Rewrite Query to get this URL:

I can do so with the following .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.

Example users.php:


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



Array ( [name] => ranjeet )

You could also redirect everything to index.php and route it through there.

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

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. How to Use Promise.all with Async/Await
  2. Connecting React App to firebase
  3. How to Promisify an Ajax Call?
  4. How to Connect Python with Database

Leave a Comment