Mod rewrite URL with 2 question marks?

A colleague asked me for some help with a few RewriteRules in his .htaccess today. One of the links he was trying to rewrite was unusual in the fact that is had 2 question marks “?” in it.

Let’s say the url looked like:'t-know?

and you wanted to rewrite that to:

You might think the rewrite would be simple, like so:

RewriteRule ^2009/1/is-this-a-legit-url\?-don%27t-know\?/?$ /2009/1/is-this-a-legit-url-i-dont-know/? [R=301,NC,L]

If you run that though, apache will throw a wobbly and tell you that “The requested URL /2009/1/is-this-a-legit-url was not found on this server.”

The reason for this is the server thinks everything after the first “?” is the querystring, so in this case, the apache is looking for a file/folder called “/2009/1/is-this-a-legit-url” and it will pass the querystring through as “-i-don’t-know?”

Of course, the simple solution would be to just match up to the first question mark in the rule, but that might not always be appropriate – e.g. if the string began with a question mark for whatever reason!

We came up with a cunning workaround for this by matching both the request url and the querystring like so:

RewriteCond %{QUERY_STRING} ^-i-don%27t-know\?/?$ [NC]
RewriteRule ^2009/1/is-this-a-legit-url$ /2009/1/is-this-a-legit-url-i-dont-know/? [R=301,NC,L]

Now, if a request like the original one above comes in, the query string will match the rewrite condition, and the requested URL will match the rewrite rule! 🙂

Note the extra question mark at the end of the rewritten rule “/is-this-a-legit-url-i-dont-know/? [R=301,NC,L]” – you need that in there to stop the server trying to push the original query string through.

Without it, your URL will be redirected to:

Unfortunately, using this method does mean that if you have any variable in the query string that you want to push through, you won’t be able to… Chances are though, that if you have 2 question marks, something’s gone wrong anyway, so this fix is better than nothing! 😉

leave your comment