Removing the trailing slash from a URL with nginx
Solution 1:
Having this regex on your server
block:
rewrite ^/(.*)/$ /$1 permanent;
would redirect all trailing slash URL's to the respective non trailing slash.
Solution 2:
Never use rewrite:
location ~ (?<no_slash>.*)/$ {
return 301 $scheme://$host$no_slash;
}
Solution 3:
I was able to get my desired behavior by using this as the final server
block in my configuration:
server {
server_name example.com 123.45.67.89 localhost;
listen 80 default_server;
# Redirect /foobar/ and /foobar/index.html to /foobar
rewrite ^(.+)/+$ $1 permanent;
rewrite ^(.+)/index.html$ $1 permanent;
root /usr/share/nginx/www/example.com;
index index.html;
try_files $uri $uri/index.html =404;
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}