添加一个新的位置块来处理您的主页,并使用 try_files 指令(而不是“index index.html;”)直接查找 index.html 文件。请注意,try_files 要求您至少输入 2 个选择。所以我把同一个文件放了两次。
location = / {
root /usr/share/nginx/www.mydomain.com/public;
try_files /index.html /index.html;
}
根据我的实验看起来不错:
curl -iL http://www.mydomain.com/index.html
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Sat, 16 Mar 2013 09:07:27 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Location: http://www.mydomain.com/
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 16 Mar 2013 09:07:27 GMT
Content-Type: text/html
Content-Length: 4
Last-Modified: Sat, 16 Mar 2013 08:05:47 GMT
Connection: keep-alive
Accept-Ranges: bytes
[UPDATE]
重定向循环的根本原因是“index”指令,它触发nginx再次进行另一轮位置匹配。这就是位置块之外的重写规则再次执行的方式,从而导致循环。所以“index”指令就像“rewrite...last;”指示。在你的情况下你不希望这样。
诀窍是不再触发另一个位置匹配。 try_files 可以有效地做到这一点。这就是为什么我在原来的答案中选择了它。但是,如果您愿意,另一个简单的修复方法是替换
index index.html;
by
rewrite ^/$ /index.html break;
在原来的“location /”块内。这个“重写...中断”;指令将使 nginx 保持在同一位置块内,有效地停止循环。然而,这种方法的副作用是您失去了“index”指令提供的功能。
[UPDATE 2]
实际上,index指令在rewrite指令之后执行。所以下面的方法也有效。请注意,我刚刚添加了重写...break;线。如果请求uri为“/”,nginx首先从重写规则中查找现有文件/index.html。因此,该请求永远不会触发索引指令。因此,这两个指令可以一起工作。
location / {
root /usr/share/nginx/www.mydomain.com/public;
index index.html;
rewrite ^/$ /index.html break;
}