我希望我网站上的以下 URL 是等效的:
/foo/bar
/foo/bar/
/foo/bar/index.html
此外,我希望后两种形式将 HTTP 301 重定向到第一种形式。我只是提供静态页面,它们是按照第三种形式排列的。(换句话说,当用户请求时,/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
_ 如何让 nginx 以我描述的方式将 URL 映射到文件?/foo/bar
/foo/bar/
编辑:我的完整配置
这是我的全部内容nginx.conf
,我的域名替换为“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;
}
}
}
server
在你的块上有这个正则表达式:会将所有尾部斜杠 URL 重定向到相应的非尾部斜杠。
永远不要使用重写:
server
通过将其用作配置中的最后一个块,我能够获得所需的行为:使用它来托管来自 Next.js (v9&v10) 静态站点生成的站点,这些站点
host/url
在host/url/
触发 Nginx 404 时工作。此规则将处理任意数量的尾部斜杠并保留 URL。它还将处理基本 URL 尾部斜杠