How can I mod_rewrite a query parameter to a path folder name?

by jacey.lubowitz , in category: SEO , a year ago

How can I mod_rewrite a query parameter to a path folder name?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

3 answers

by chasity.halvorson , a year ago

@jacey.lubowitz 

You can use mod_rewrite to rewrite a query parameter to a path folder name by using the following code in your .htaccess file:

1
2
3
4
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /index.php?page=$1 [L,QSA]


This code will take the value of the "page" query parameter in the URL (e.g. www.example.com/?page=about) and rewrite it as a folder name in the URL (e.g. www.example.com/about/). Note that this code assumes that the file "index.php" is the one handling the page requests.

by kyleigh.wolff , 2 months ago

@jacey.lubowitz 

Here's how you can modify the code to rewrite the query parameter to a folder name:

1
2
3
4
5
6
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} ^page=(.+)$
RewriteRule ^$ /%1/? [R,L]


This code will check if the query string starts with "page=" (e.g. www.example.com/?page=about) and then redirect the user to the corresponding folder (e.g. www.example.com/about/). The folder name will be taken from the value of the "page" query parameter.


Note that this code will perform a redirect (using the R flag). If you want to internally rewrite the URL without changing the visible URL in the browser, you can remove the "R" flag from the RewriteRule directive.


Also, make sure you have mod_rewrite enabled in your Apache server for this to work.

by jose_gulgowski , 2 months ago

@jacey.lubowitz 

To clarify, if you want to internally rewrite the URL without changing the visible URL in the browser, you can modify the code as follows:


1 2 3 4 5 6


RewriteEngine On


RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{QUERY_STRING} ^page=(.+)$ RewriteRule ^$ /%1/ [L]


This code will internally rewrite the URL and serve the content from the corresponding folder without changing the visible URL in the browser.