I recently worked on a website where I had to redirect over 100+ URLs besides 1000+ existing URL redirection! Here is what I learned.
I found out that the existing URL redirection was added using Nginx rewrite rules which are usually found in the Nginx configuration location block.
A rewrite rule expects 3 arguments.
- A regex capture string
- A regex replacement string
- A rewrite type value (permanent, rewrite)
Examples
For example: rewrite /capture-url http://external-website.com/replacement-url permanent;
In this example, a request for /capture-url will be redirected to http://external-website.com/replacement-url.
While adding the new URL redirections I faced some issues with the URL with the query string, I was supposed to redirect a URL with an exact match for the query string also which was not possible with only the 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 an exact match URL with a query string from –
http://my-website/capture-url?a=1&b=2&c=3
to
http://my-website/replacement-url?x=1&y=2&z=3
When we use the 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
http://my-website/replacement-url?x=1&y=2&z=3&whatever-query-string-is-passed-at-capture-string
To accomplish my requirement I have modified the config as follows-
location = /capture-url
And it works perfectly for me!
While trying this solution I have found another important issue if the capture-url and replacement-url are the same while redirecting with the location block it will fall into the dead loop so we have to be careful about that.
For example, suppose we have to redirect an exact match with the query string for
http://my-website/common-url?a=1&b=2&c=3 to
http://my-website/common-url?x=1&y=2&z=3
Now if we try
location = /common-url
This will lead us to an infinite loop, in this case, we have to make sure that the base URLs for capture-URL and replacement-URL must not be the same!
Important links-
https://blog.nginx.com/blog/creating-nginx-rewrite-rules/
https://nginx.org/en/docs/http/ngx_http_core_module.html#location
More to Explore
The Quest for Knowledge Continues. Fuel Your Curiosity.