nginx issue with following all redirects

VSack asked:

I have two redirects in a file at /etc/nginx/redirect.conf:

rewrite /this-link https://www.google.com redirect;
rewrite /this-link-too https://mail.google.com redirect;

Attempting to go to http://www.example.com/this-link or http://www.example.com/this-link-too both go to https://www.google.com.

Is there a way to force exact matching?

Example config below:

server {
listen 80;

server_name www.example.com;

index index.html;

error_page 404 http://www.example.com/error.html;

location / {
  try_files $uri @redirect;
}

location @redirect {
  include /etc/nginx/redirect.conf;
}

My answer:


The rewrite directive accepts a regular expression, so /this-link-too matches /this-link, and thus your first rewrite always gets used. Rewrite should be avoided unless you actually need to match a regular expression or do substitutions.

You should consider using exact location matches with return instead.

For example:

location = /this-link {
    return 302 https://www.google.com/;
}

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.