NGINX redirect rule transform path to query string

nginxrewrite

We have one existing IIS app that was running with Helicon APE to rewrite urls using existing Apache rules. This is one example:

RewriteRule ^/webapp/([^/]*)/([^/]*)(/.+)? /webapp/$4?$2=$3 [NC,L,P,QSA]

For these rules, an original url like /webapp/f6/3/gx/1/default.htm gets transformed into /default.htm?f6=3&gx=1. This supports a variable number of intermediate paths in APE (apparently in Apache, too).

Since APE does not scale well and crashes under load, I've started setting a NGINX that will do the rewrites and perform load balancing for the IIS servers in the back.

One problem I've found, though: the same rule for nginx rewrites don't work the same way; I had to transform it to get it matching:

rewrite ^/webapp/(.*)/([^/]+).htm /webapp/$2?$1;

which, in fact, for /webapp/f6/3/gx/1/default.htm returns /webapp/default.htm?f6/3/gx/1.

I've been trying to find a way of making nginx to convert path elements /x/y/g/z into query string pairs ?x=y&g=z. Apache seems to make it automatically, while nginx does not, and can't find anything in the documentation or in other questions in this site, or StackOverflow.

Apparently using map this could be done, but can't find a specific usage, and I'm not an expert on nginx to get this done. Any help or indication. will be welcome.

Best Answer

If you construct the rewrite rule correctly, it will become recursive and query parameters on each iteration until all of the path elements are consumed.

For example:

rewrite ^(/webapp)/([^/]+)/([^/]+)(/.+)$ $1$4?$2=$3 redirect;

As rewrite automatically appends an existing query string, the above statement extends it with each redirect.

The same trick can be achieved with an internal redirect by placing a rewrite...last statement within a location block.

See this document for more.

Related Topic