Nginx: `proxy_pass` Without Trailing Slash

The URLs with and without trailing slash are considered by web-servers as well as by search engines as different web-pages.

By this reason the URLs with trailing slash may return 404 Not Found error, while without the trailing slash they are reachable.

In this note i will show how to remove the trailing slash from URLs in Nginx and proxy_pass the traffic without them.

Cool Tip: Reload Nginx inside Docker container! Read more →

Nginx `proxy_pass` Without Trailing Slash

Add the following rewrite rule in the server section of the Nginx config to remove the trailing slash from all URLs and proxy_pass the traffic to the upstream cluster:

server {
  listen 80;
  server_name example.tld;

  # Remove trailing slash from URLs
  rewrite ^/(.*)/$ /$1 permanent;

  location / {
      proxy_pass         http://$upstream;
      proxy_redirect     off;
  }
}

The rule above creates SEO-friendly 301 Moved Permanently redirect from all URLs with the trailing slash to the same URLs without them:

$ curl -IL http://example.tld/path/
HTTP/1.1 301 Moved Permanently
server: nginx
location: http://example.tld/path
...
HTTP/1.1 200 
server: nginx
...