Configuring htaccess/mod_rewrite to serve static files with question mark in the URL

.htaccessapache-2.2mod-rewrite

I've just taken on hosting of an ancient site that was converted from asp to static html, consisting of about 6,000 files. However, my server doesn't like the filenames, giving a 404 error. The URLs are all of the form:

filename.asp?id=123&a=something.html

where id is always an integer and a is always a string of characters & numbers.

Is there any way I can use htaccess and mod_rewrite to tell it that the question mark is part of the URL rather than signifying a query string?

Best Answer

You probably already know you are not the first person to have this need :)

# Allow filenames containing '?' to be served by escaping the '?' in the HTTP
# request so it's not interpreted as a query string.
#
# Apache 2.2: set query string to empty by ending rewritten path with '?'.
# Apache 2.4: use the qsdiscard flag instead
#
RewriteCond %{QUERY_STRING} !=""
RewriteRule ^/(.*) /$1\%3F%{QUERY_STRING}? [noescape,last,redirect]

The key is the combination of adding a redirect and NE/noescape to ensure apache doesn't escape what we don't want escaped.

The above rule will mean that the entire site under this rewrite will treat ? as part of the filename. If you need to have it match your filename.asp - just add it to the RewriteRule

Related Topic