我在 Nginx 上有一个简单的静态网站,我正在尝试实现从 mysite.com/index.html 到 mysite.com 的重定向,以便对搜索引擎更友好。但我遇到了重定向循环。我写了这条规则:
location = /index.html {
rewrite ^ http://mysite.com permanent;
}
进行一些测试后,我注意到如果我重定向到 404 页面,一切都正常:
rewrite ^ http://mysite.com/404.html permanent;
这是完整的配置文件:
server {
listen 80;
server_name www.mysite.com;
rewrite ^/(.*) http://mysite.com/$1 permanent;
}
server {
listen 80;# default_server;
listen ipaddress:80;
server_name mysite.com;
access_log /var/www/mysite.com/logs/access.log;
error_log /var/www/mysite.com/logs/error.log;
root /var/www/mysite.com/htdocs;
error_page 404 /404.html;
location = /index.html {
rewrite ^ http://mysite.com permanent;
}
}
答案1
你这样做是错的。
server {
listen 80;
server_name www.mysite.com;
return 301 http://mysite.com$request_uri;
}
server {
listen 80 default_server;
server_name mysite.com;
access_log /var/www/mysite.com/logs/access.log;
error_log /var/www/mysite.com/logs/error.log;
root /var/www/mysite.com/htdocs;
error_page 404 /404.html;
location / {
try_files $uri $uri/index.html =404;
}
location = /index.html {
return 301 http://mysite.com/;
}
}