Published On: March 13th, 20182.2 min read

I recently worked on a website where I have to redirect over 100+ URLs besides 1000+ existing URL redirection! Here is what I learned.

I find out that the existing URL redirection was added using Nginx rewrite rules which are usually found in nginx configuration location block.

A rewrite rule expects 3 arguments.

  1. A regex capture string
  2. A regex replacement string
  3. A rewrite type value (permanent, rewrite)

For example: rewrite /capture-url permanent;

In this example, a request for /capture-url will be redirected to

While adding the new URL redirections I faced some issues with url with query string, I was supposed to redirect an url with an exact match for query string also which was not possible with only redirect rule as it doesn’t match the query string, only the base url and add the query string from capture string at the end of the replacement string.

For example, We want to redirect on exact match URL with query string from –

When we use following configuration-
rewrite /capture-url?a=1&b=2&c=3 http://my-website/replacement-url?x=1&y=2&z=3 permanent;

It was ignoring the query string match for the capture string and adding whatever query string is passed to the capture string as the query string for replacement string, it was redirecting to

To accomplish my requirement I have modified the config as follows-

location = /capture-url {
 if ($args ~* "a=1&b=2&c=3") {
  set $args "x=1&y=2&z=3";
  rewrite ^.*$ http://my-website/replacement-url permanent;

And it works perfectly for me!

While trying this solution I have find out another important issue that if the capture-url and replacement-url are same while redirecting with location block it will fall into dead-loop so we have to be careful about that.

For example suppose we have to redirect on exact match with query string for

http://my-website/common-url?a=1&b=2&c=3 to


Now if we try

location = /common-url {
 if ($args ~* "a=1&b=2&c=3") {
  set $args "x=1&y=2&z=3";
  rewrite ^.*$ http://my-website/common-url permanent;

This will lead us to an infinite loop, in this case, we have to make sure that base URLs for capture-url and replacement-url must not be same!

Important links-

Contributor: Shafiqul Kader , Nascenia

Share it, Choose Your Platform!

More to Explore

The Quest for Knowledge Continues. Fuel Your Curiosity.