nginx:重写规则,从$ request_uri中删除/index.html [英] nginx : rewrite rule to remove /index.html from the $request_uri

查看:732
本文介绍了nginx:重写规则,从$ request_uri中删除/index.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当文件系统中存在特定文件时,我已经看到了几种重写$request_uri并将index.html添加到其中的方法,例如:

I've seen a few ways to rewrite the $request_uri and add the index.html to it when that particular file exists in the file system, like so:

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

但是我想知道相反的情况是否可以实现:

but i was wondering if the opposite is achievable:

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

i.e. when somebody requests http://example.com/index.html, they're redirected to http://example.com

因为nginx regexp与perl兼容,所以我尝试了如下操作:

Because the nginx regexp is perl compatible, i tried something like this:

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

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

but it was mostly a guesswork, is there any good documentation describing the modrewrite for nginx ?

推荐答案

我在顶级服务器子句中使用以下重写:

I use the following rewrite in the top level server clause:

rewrite ^(.*)/index.html$ $1 permanent;

单独使用此功能可用于大多数URL,例如http://foo.com/bar/index.html,但会破坏http://foo.com/index.html.要解决此问题,我有以下附加规则:

Using this alone works for most URLs, like http://foo.com/bar/index.html, but it breaks http://foo.com/index.html. To resolve this, I have the following additional rule:

location = /index.html {
  rewrite  ^ / permanent;
  try_files /index.html =404;
}

当找不到文件时,=404部分将返回404错误.

The =404 part returns a 404 error when the file is not found.

我不知道为什么仅靠第一次重写是不够的.

I have no idea why the first rewrite alone isn't sufficient.

这篇关于nginx:重写规则,从$ request_uri中删除/index.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆