Last Updated: February 25, 2016
·
14.8K
· jsolis

nginx.conf query string processing

Here is a snippet of code I wrote recently that processed a query string parameter and turned it into a cookie. The business rules were that given a query string that looked like this:

?refid=PLNODEJS&refclickid=MEOW

I had to set a cookie named "referral" which looked like this

SOURCEID=PL&ID=NODEJS&PRODUCTID=&WEBENTRYTIME=1391464544&CLICKID=MEOW

The first two characters of the "refid" query parameter had to be broken out separately from the rest, the time had to be stored, and a second query string parameter named "refclickid" had to be munged into there as well.

Ugh, messy. We used to do this processing on an application level but due to different teams not doing everything the same way, we decided to try throwing this logic into an nginx.conf

if ($query_string ~* "refid=([a-zA-Z0-9]{2})([^&]*)") {
    set $refSource $1;
    set $refid $2;
    set $refcookievalue SOURCEID=$refSource&ID=$refid&PRODUCTID=&WEBENTRYTIME=$date_local;
}
if ($query_string ~* "refclickid=([^&]*)") {
    set $refclick $1;
    set $refcookievalue $refcookievalue&CLICKID=$refclick;
}
add_header Set-Cookie Referral=$refcookievalue;