How To Use Apache Rewrite Rules to Dynamically Add Query String Parameters


Let’s say you have a client app that needs to connect to a third party backend system via your servers. The backend requires several query parameters (the part of the URL after the “?”) to be specified in the request (say, bit rate ranges for a given video configuration) but for business reasons you can’t have requests that carry query parameters. How do you get the relevant parameters to the backend? Apache rewrite rules is how! So let’s say that instead of query string parameters, the client sends an identifying string in the URL path:

Here we are interested in the video_set1_dash.mpd part. This is a predetermined token that maps to a particular set of video attributes. This request will come into our proxy server, where we want to rewrite it into something like this before sending on to the third-party backend system:"video"%26%26systemBitrate==500000)||(type=="video"%26%26systemBitrate==3704052)

We can do this in Apache by adding a rewrite rule. First import the module via your global Apache config:

LoadModule rewrite_module modules/

Then add the rewrite rule:

RewriteRule ^(.*)\/(.*)_dash\.mpd$ $1/.mpd?${filterMap:$2|?notFound}

The first part,  ^(.*)\/(.*)_dash\.mpd$, is a regex that matches the identifier token  (#2) and the preceding path (#2).

The second part, $1/.mpd?${filterMap:$2|?notFound} instructs apache to rewrite the URL so that we have the preceding path followed by whatever the token maps to in ‘filterMap‘.

This filterMap is defined elsewhere in the Apache config as a file containing something like this:

video_set1_dash filter=(type=="video"%26%26systemBitrate==500000)||(type=="video"%26%26systemBitrate==3704052)
video_set2_dash filter=(type=="video"%26%26systemBitrate==500000)||(type=="video"%26%26systemBitrate==3704052)

Here you can see that our token, video_set1_dash, maps to a set of query parameters, so voila, we have what we need:"video"%26%26systemBitrate==500000)||(type=="video"%26%26systemBitrate==3704052)

You might have noticed that there is ?notFound clause in the rewrite rule. This is for cases where no match is found in the filterMap, and simply adds ‘noMatch’ to the URL:

We can then pick this up with a later bit of config and return a 404:

RewriteCond %{QUERY_STRING} notFound
RewriteRule ^(.*)\/.mpd$ - [R=404]

And there you have it! It’s a neat little trick that can be used in a variety of different contexts 🙂 Let me know what you think in the comments below, and I’ll see you again in my next post!










Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s