2011-04-15 242 views
4

我已经看到了一些方法来重写$request_uri并添加index.html,就当该特定文件在文件系统中存在,像这样删除/index.html:

if (-f $request_filename/index.html) { 
    rewrite (.*) $1/index.html break; 
} 

,但我想知道如果对面是可以实现的:

即当有人请求http://example.com/index.html,他们重定向到http://example.com

由于nginx的正则表达式是Perl兼容的,我想小号像这样:

if ($request_uri ~* "index\.html$") { 
    set $new_uri $request_uri ~* s/index\.html// 
    rewrite $1 permanent; 
} 

但它主要是猜测,是否有任何好的文档描述nginx modrewrite?

回答

6

我用下面的改写顶级服务器子句:

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; 
} 

时未找到该文件的=404部分返回404错误。

我不知道为什么第一次重写是不够的。

1

对于根/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/; 
} 
0

这一个工程:

# redirect dumb search engines 
location /index.html { 
    if ($request_uri = /index.html) { 
     rewrite^http://$host? permanent; 
    } 
} 
1

出于某种原因,大多数在这里提到的解决方案没有奏效。那些工作给了我错误的遗漏/在网址。这个解决方案适用于我。

粘贴您的位置指令。

if ($request_uri ~ "/index.html") { 
    rewrite ^/(.*)/ /$1 permanent; 
} 
0

引用$scheme://domain.com/的解决方案假定该域是硬编码的。这不是在我的情况,所以我用:

location/{ 
    ... 

    rewrite index.html $scheme://$http_host/ redirect; 

    ... } 
+0

嗨,这看起来不错,但你也解释(对我们新手)为什么新的解决方案更好地工作? – 2013-06-25 00:12:13

+1

这是nginx配置中的一个特点。我经验地发现(我可能错了),没有办法以相对的方式引用根的'/'页面。所以我被委托以绝对的方式提及它,为此我们必须提供完整的方案和主机名(域名)。 这个小黑客让我们可以参考域名而不必对其进行硬编码。我发现它特别有用,因为我正在开发和使用该站点的单独登台和Vagrant(虚拟机)版本。 – 2013-07-03 21:03:14

2

以下配置让我/index.html重定向到//subdir/index.html/subdir/

# Strip "index.html" (for canonicalization) 
if ($request_uri ~ "/index.html") { 
    rewrite ^(.*)/ $1/ permanent; 
} 
1

这是为我工作:

rewrite ^(|/(.*))/index\.html$ /$2 permanent; 

它涵盖了根实例/index.html和较低的情况下/bar/index.html

正则表达式的第一部分主要翻译为:[nothing]/[something] - 在第一种情况下$ 2是一个空字符串,所以你重定向到刚刚/,在第二种情况下$ 2是[something],所以你重定向到/[something]

其实我去有点票友覆盖index.htmlindex.htmindex.php

rewrite ^(|/(.*))/index\.(html?|php)$ /$2 permanent; 
+0

这使我处于一个无限的重定向循环,因为它试图将https重定向到http,然后我的负载均衡器将其重定向到https – djsumdog 2018-02-11 07:48:30

+0

这很令人惊讶,我认为它只是一个双重重定向,nginx会剥离索引。 html并切换到http,然后负载平衡器重定向回https(但仍然没有index.html)。看起来你的nginx并不知道它应该把“https”放在绝对URL中,也许你可以在重写语句中手动执行它,而不是“/ $ 2”也许https:// $ host/$ 2 – barryp 2018-02-14 15:30:26