在 nginx 上配置一些重写规则时,我正在为这个抓狂。我在 Debian Wheezy 机器上运行 nginx 1.2.1。
考虑以下树:
/
├── index.html
├── folder/
│ └── index.html
└── file.html
我希望这些文件由 nginx 提供服务,这样就不需要在 URL 中指定任何 .html
,并且不需要对 folder/index.html 进行任何调用
在 folder/
中重写,对 file.html
的任何调用都在 index
中重写。
这是此描述的正式版本。请求示例位于左侧,我尝试获取的相应响应位于右侧(HTTP 代码 301 + 重定向位置或 HTTP 代码 200 + 要显示的文件):
1. http://example.com/ -> 200 (/index.html)
2. http://example.com/index.html -> 301 http://example.com/
3. http://example.com/index -> 301 http://example.com/
4. http://example.com/file -> 200 (/file.html)
5. http://example.com/file.html -> 301 http://example.com/file
6. http://example.com/folder/ -> 200 (/folder/index.html)
7. http://example.com/folder -> 301 http://example.com/folder/
8. http://example.com/folder/index.html -> 301 http://example.com/folder/
9. http://example.com/folder/index -> 301 http://example.com/folder/
10. http://example.com/foobar -> 404
到目前为止,我最接近的尝试是 /etc/nginx/sites-enabled/example.com
的以下配置:
server {
server_name example.com;
root /var/www/example.com/public_html;
rewrite ^(.*/)index(\.html)*$ $1 permanent; # Applies to 2, 3, 8, 9
rewrite ^(/.+)\.html$ $1 permanent; # Applies to 5
try_files $uri $uri.html "${uri}index.html" =404; # Handles 1, 4, 6, 10
}
如您所见,缺少案例7
。现在,我得到了:
7'. http://example.com/folder -> 404
我还设法拥有:
7''. http://example.com/folder -> 200 (/folder/index.html)
但这绝对是我不希望 SEO 明智的事情(除其他外),因为 2 个不同的 URL(带或不带尾部斜杠)返回相同的内容。
每个配置都没有通过我的所有测试用例。
请注意,当我简单地禁用 2 个 rewrite
和 try_files
时,7
按预期应用(以及 1
、6
、10
,但其他除外),重定向默认有效。我不明白这个重定向规则是如何以及在哪里进行的,所以这是我的正式问题:如何使这个重定向重新出现,以及如何让我的 10 个测试用例正常工作?
非常感谢,我是认真的:)
PS:我尽力了,但当然,如果有任何不清楚的地方,请随时要求澄清!
最佳答案
你有一些错误,首先你不会做任何 301 重定向,如果你正在访问某些东西,那么你会使用重定向,但随后你希望它转到其他东西,例如,如果我们正在做一个升级。
http://example.com/index.html =>redirects to=> http://example.com/maintenance.html
您需要的是将某些内容的格式更改为其他内容,顺便说一句,您的重写会被交换,重写工作就像这样
rewrite [what to match] [what to do with it]
您的重写是说,当我获得 /index.html
的 URL 时,它将重定向到 /index
,然后会给您一个 404
> 因为你没有一个名为 /index
我想用 try_files
来实现
server {
server_name example.com www.example.com;
root /my/root/path;
location / {
try_files $uri $uri/ $uri.html;
}
试试这个并告诉我效果如何。
关于redirect - 如何重定向并删除 URL 中的 .html 扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19020642/