Home How can I mod_rewrite and keep query strings?
Reply: 1

How can I mod_rewrite and keep query strings?

Daniel Oakey
1#
Daniel Oakey Published in 2012-10-13 12:33:02Z

I want to mod_rewrite a URL to another page, but then I also want any query strings added to be preserved.

RewriteEngine On

#enforce trailing slashes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !#
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://localhost/siteroot/$1/ [L,R=301]

RewriteRule ^apps/([A-Za-z0-9-_]+)/?$ index.php&app=$1

So if a user visits apps/app1/, index.php?app=app1 is shown. However, I want to be able to preserve optional query strings, so that visiting apps/app1/?variable=x returns index.php?app=app1&variable=x.

What mod_rewrite rule/condition would make this happen?

Michael Berkowski
2#
Michael Berkowski Reply to 2012-10-13 12:40:34Z

You need to add the [QSA] flag ("query string append")

RewriteRule ^apps/([A-Za-z0-9-_]+)/?$ index.php&app=$1 [L,QSA]

For page 301 redirects with the [R] flag as opposed to internal rewrites like this one, the query string is automatically appended. However, you must force it with [QSA] for the internal rewrite.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.426425 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO