Rewrite to append to query string

.htaccess, apache, mod-rewrite

Solution

You can't match against the query string within a `RewriteRule`, you need to match against the `%{QUERY_STRING}` variable in a `RewriteCond`. However, if you want to just append the query string, you can just use the `QSA` flag:

RewriteRule /cia16(.*) /cia/$1?CIA=16 [QSA]

The URI: `/cia16/steps.php?page=1` would get rewritten to `/cia/steps.php?CIA=16&page=1`. If for some reason, you need the `page=1` before the `CIA=16`, then you can do something like this:

RewriteRule /cia16(.*) /cia/$1?%{QUERY_STRING}&CIA=16

Problem

I don't understand why I always have such a massive problem with rewrite rules, but I simply want to append to the query string if it exists and add a `?` if it does not. I actually don't care if the URL is changed in the browser or not -- it just has to load the correct target page. ``` RewriteRule /cia16(.*)\?(.*) /cia$1?$2&CIA=16 RewriteRule /cia16(.*) /cia/$1?CIA=16 ``` If I go to `/cia16/steps.php?page=1` it actually gets rewritten to `/cia/steps.php?CIA=16` -- that is it seems accept the query string part is not even considered part of the URL for the purposes of the rewrite. What do I have to do to get the rewrite to work properly with an existing query string?

Original source