Apache Pretty URLs with ?foo=bar parameters.

I recently had the problem that I needed to have pretty urls with get parameters of the form:

http://my.site.com/article/article1?page=3

http://my.site.com/article/article2?page=5

Where article1 and article2 would each map to the same underlying PHP script, processor.php, and pass it parameters ?article=<id>&page=<pgnum>. I found many postings on the net demonstrating how to achieve pretty URLs in apache configuration like so:


RewriteRule ^/article/(.*)/?$ %{DOCUMENT_ROOT}/processor.php?article=$1

Or a similar variations of that.

So I figured that to pass the remainder of the query string something like this should work:


RewriteRule ^/article/(.*)/?\??(.*)$ %{DOCUMENT_ROOT}/processor.php?cmd=$1&$2

Where we would append everything after ? in the original query string and place it after & in our new one.

But alas, no.

mod_rewrite wanted nothing to do with that. No matter what regex I tried, my ?page=3 argument was not getting through to my PHP script.

Fortunately, mod_rewrite does offer a solution. Just append [QSA]. Like so:


RewriteRule ^/article/(.*)/? %{DOCUMENT_ROOT}/processor.php?article=$1 [QSA]

The mod_rewrite docs have this to say on the matter:

Modifying the Query String

By default, the query string is passed through unchanged. You can, however, create URLs in the substitution string containing a query string part. Simply use a question mark inside the substitution string to indicate that the following text should be re-injected into the query string. When you want to erase an existing query string, end the substitution string with just a question mark. To combine new and old query strings, use the [QSA] flag.

So by including a ? in my original substitution rule I was effectively erasing and replacing the existing query string. But QSA brings back the other parameters, and my problem is solved.

Facebook Comments

comments

Posted in post