使用nginx从URL中删除尾部的斜杠

我想在我的网站上的以下url是等效的:

/foo/bar /foo/bar/ /foo/bar/index.html 

进一步,我想第二个两个表格发出HTTP 301redirect到第一种forms。 我只是服务静态页面,并按照第三种forms进行排列。 (换句话说,当用户请求/foo/bar他们应该接收/usr/share/.../foo/bar/index.html文件)。

我的nginx.conf目前包含以下内容:

 rewrite ^(.+)/$ $1 permanent; index index.html; try_files $uri $uri/index.html =404; 

这适用于/foo/bar/index.html请求,但是当我请求/foo/bar/foo/bar/ Safari告诉我“发生了太多的redirect” – 我假设有一个无限的redirect循环或类似的东西。 我怎样才能让nginx以我描述的方式将URL映射到文件?

编辑:我的完整configuration

这是我的整个nginx.conf与我的域名replace“example.com”。

 user www-data; worker_processes 1; pid /run/nginx.pid; events { worker_connections 768; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; server_tokens off; server_names_hash_bucket_size 64; include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss application/atom+xml text/javascript image/svg+xml; server { server_name www.example.com; listen 80; return 301 $scheme://example.com$request_uri; } server { server_name example.com 123.45.67.89 localhost; listen 80 default_server; # Redirect /foobar/ to /foobar rewrite ^(.+)/$ $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; } } } 

有这个正则expression式在你的server块:

 rewrite ^/(.*)/$ /$1 permanent; 

会将所有结尾的斜杠URLredirect到相应的非结尾斜杠。

我可以通过使用这个作为我的configuration中的最后一个server块来得到我想要的行为:

 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; } }