问题描述
||
当文件系统中存在该特定文件时,我已经看到了几种重写re0并将ѭ1添加到其中的方法,例如:
if (-f $request_filename/index.html) {
rewrite (.*) $1/index.html break;
}
但我想知道相反的情况是否可以实现:
也就是说,当有人要求http://example.com/index.html
时,他们会被重定向到http://example.com
因为Nginx regexp是与perl兼容的,所以我尝试了如下操作:
if ( $request_uri ~* \"index\\.html$\" ) {
set $new_uri $request_uri ~* s/index\\.html//
rewrite $1 permanent;
}
但这主要是一个猜测,是否有任何好的文档描述Nginx的modrewrite?
解决方法
我在顶级服务器子句中使用以下重写:
rewrite ^(.*)/index.html$ $1 permanent;
单独使用此选项可用于大多数URL,例如http://foo.com/bar/index.html
,但会破坏http://foo.com/index.html
。要解决此问题,我有以下附加规则:
location = /index.html {
rewrite ^ / permanent;
try_files /index.html =404;
}
找不到文件时,“ 10”部分将返回404错误。
我不知道为什么仅靠第一次重写是不够的。
,以下配置允许我将/index.html
重定向到/
并将/subdir/index.html
重定向到/subdir/
:
# Strip \"index.html\" (for canonicalization)
if ( $request_uri ~ \"/index.html\" ) {
rewrite ^(.*)/ $1/ permanent;
}
,对于根/index.html
,Nicolas的答案导致了重定向循环,因此我不得不搜索其他答案。
在nginx论坛上提出了这个问题,那里的答案效果更好。
http://forum.nginx.org/read.php?2,217899,217915
使用任一
location = / {
try_files /index.html =404;
}
location = /index.html {
internal;
error_page 404 =301 $scheme://domain.com/;
}
要么
location = / {
index index.html;
}
location = /index.html {
internal;
error_page 404 =301 $scheme://domain.com/;
}
,由于某种原因,此处提到的大多数解决方案均无效。起作用的那些给我错误,网址中缺少/。此解决方案对我有用。
粘贴到您的位置指令中。
if ( $request_uri ~ \"/index.html\" ) {
rewrite ^/(.*)/ /$1 permanent;
}
,这为我工作:
rewrite ^(|/(.*))/index\\.html$ /$2 permanent;
它涵盖了根实例/index.html
和下层实例/bar/index.html
正则表达式的第一部分基本上翻译为:[nothing]
或/[something]
-在第一种情况下$ 2是一个空字符串,因此您重定向到just12ѭ,在第二种情况下$ 2是[something]
因此您将重定向到/[something]
我实际上更喜欢index.html
,index.htm
和index.php
rewrite ^(|/(.*))/index\\.(html?|php)$ /$2 permanent;
,这个作品:
# redirect dumb search engines
location /index.html {
if ($request_uri = /index.html) {
rewrite ^ $scheme://$host? permanent;
}
}
,引用ѭ33的解决方案假定该域是硬编码的。这不是我的情况,因此我使用了:
location / {
...
rewrite index.html $scheme://$http_host/ redirect;
... }