37

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?

Daniel Oakey
  • 405
  • 1
  • 4
  • 7

1 Answers1

75

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.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • Thanks, I didn't realise it was that simple. – Daniel Oakey Oct 13 '12 at 12:42
  • 1
    +1 Agree with @DanielOakey.. I was trying to hack something with regex and it wasnt working.. – Karthik T Mar 16 '14 at 13:59
  • 2
    To clarify, it's not about rewrites vs redirects. http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsa says: When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined. – Denis Howe Nov 08 '16 at 11:24
  • 2
    Maybe you guys already know, but make sure to leave NO SPACE before `QSA`. That's gonna end up in a HTTP 500... – Romeo Sierra Sep 13 '21 at 03:11