Search code examples
nginxhttp-redirecthttp-status-code-301

How can I do a 301 redirect towards an URL ending in a slash with Nginx?


I've an nginx web server that proxy pass traffic to different services on my LAN. After a recent update of one of those services the redirect stop working as expected. The service behind the redirect is Pi-Hole so I can't/wan't modify how the web service works. I just want to fix the redirect.

My actual nginx configuration looks like this:

server {
  listen 80;
  listen [::]:80;
  server_name servername.xyz localhost default;

  access_log /var/log/nginx/servername-xyz.access.log;
  error_log /var/log/nginx/servername-xyz.error.log;

  location = /pihole {
    return 301 http://servername.xyz/pihole/admin;
  }

  location = /pihole/ {
    return 301 http://servername.xyz/pihole/admin;
  }

  location /pihole/ {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://127.0.0.1:31480/;
  }

  location = / {
    return 418;
  }
}

This configuration was working perfectly. Every time I write in my browser http://servername.xyz/pihole, I automatically get the redirect to http://servername.xyz/pihole/admin and start using the Pi-Hole web console flawless.

With the last Pi-Hole update, they make a small change that broke the redirect. Now every time you ask for http://pi-hole.domain/admin the web console is automatically redirected to http://pi-hole.domain/admin/. Note the slash at the end of the second URL.

In my configuration, that means the following behaviour:

  1. I ask the browser for http://servername.xyz/pihole
  2. I get the 301 and go to http://servername.xyz/pihole/admin
  3. Here I get a redirect that I don't expect from the Pi-Hole web console that makes me go to: http://servername.xyz/admin/. Note the ending slash.

When I get to the third step, the redirect doesn't allow me to get into the Pi-Hole web console. I've tried some changes to the rules, but I didn't succeed in my objective to get a 301 towards http://servername.xyz/admin/ to avoid the Pi-Hole web console redirect.


Solution

  • Big thanks to Richard's Smith comment. It let me fix the configuration file. Now the proxy_pass action in the file looks like:

    location /pihole/ {
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_pass http://127.0.0.1:31480/;
      proxy_redirect http://servername.xyz/admin/ http://servername.xyz/pihole/admin/;
    }
    

    After including the proxy_redirect directive, things start working again.