我希望我网站上的以下 URL 是等效的:
/foo/bar
/foo/bar/
/foo/bar/index.html
Run Code Online (Sandbox Code Playgroud)
此外,我希望后两个表单发出 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;
Run Code Online (Sandbox Code Playgroud)
这适用于 的请求/foo/bar/index.html
,但是当我请求/foo/bar
或/foo/bar/
Safari 告诉我“发生了太多重定向”——我假设存在无限重定向循环或类似的东西。如何让 nginx 以我描述的方式将 URL 映射到文件?
这是我的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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 26
在你的server
块上有这个正则表达式:
rewrite ^/(.*)/$ /$1 permanent;
Run Code Online (Sandbox Code Playgroud)
会将所有尾随斜杠 URL 重定向到相应的非尾随斜杠。
小智 8
永远不要使用重写:
location ~ (?<no_slash>.*)/$ {
return 301 $scheme://$host$no_slash;
}
Run Code Online (Sandbox Code Playgroud)
通过将其用作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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
46892 次 |
最近记录: |