6

我在磁盘上的文件有扩展名:index.html, a.html. http://example.com/a我想要一个加载/var/www/a.htmlhttp://example.com/加载的请求/var/www/index.html。我希望任何其他 url 重定向到规范 url,所以http://example.com/a.html应该重定向到http://example.com/a.

我的配置如下:

rewrite ^(/.+)\.html$ $scheme://$host$1 permanent;
location / {
    root   /var/www;
    try_files $uri.html $uri $uri/ =404;
}

这确实重定向/a.html到并成功从磁盘/a加载:a.html

$ curl -D- -s http://www.jefftk.com/food.html | grep ^Location
Location: http://www.jefftk.com/food
$ curl -s http://www.jefftk.com/food | grep ^Location

但它发送//index

$ curl -s -D- http://www.jefftk.com/pictures/ | grep ^Location
Location: http://www.jefftk.com/pictures/index
$ curl -s -D- http://www.jefftk.com | grep ^Location
Location: http://www.jefftk.com/index

如果我删除重写规则,它会停止从/a.htmlto重定向,/a但也会停止发送//index

$ curl -D- -s http://www.jefftk.com/food.html | grep ^Location
$ curl -D- -s http://www.jefftk.com/food | grep ^Location
$ curl -D- -s http://www.jefftk.com/ | grep ^Location
$ curl -D- -s http://www.jefftk.com/pictures/ | grep ^Location

为什么会发生这种情况?我可以同时为我想要的两个东西(没有.html扩展名,没有indexurl)制作 nginx 吗?

4

2 回答 2

1

我认为您的重写规则可能是倒退的。也许只是这个(没有重写规则):

location / {
    try_files $uri.html $uri $uri/ =404;
}

location = / {
    index index.html;
}

编辑版本:

对不起,我没有完全理解你的描述。我重读了几次并对此进行了测试,它可能接近您想要做的事情:

location = / {
    try_files /index.html =404;
}

location = /index {
    return 301 $scheme://$host;
}

location ~* \.html$ {
    rewrite ^(.+)\.html$ $scheme://$host$1 permanent;
}

location / {
    try_files $uri.html $uri/ @backend;
}

location @backend {
    # rewrite or do whatever is default for your setup
    rewrite ^ /index.html last;
    // or return 404;
}

代码示例(修订版 3):

我希望第三次是一个魅力。也许这会解决你的问题?

# example.com/index gets redirected to example.com/

location ~* ^(.*)/index$ {
    return 301 $scheme://$host$1/;
}

# example.com/foo/ loads example.com/foo/index.html

location ~* ^(.*)/$ {
    try_files $1/index.html @backend;
}

# example.com/a.html gets redirected to example.com/a

location ~* \.html$ {
    rewrite ^(.+)\.html$ $scheme://$host$1 permanent;
}

# anything else not processed by the above rules:
# * example.com/a will load example.com/a.html
# * or if that fails, example.com/a/index.html

location / {
    try_files $uri.html $uri/index.html @backend;
}

# default handler
# * return error or redirect to base index.html page, etc.

location @backend {
    return 404;
}
于 2012-12-20T00:31:40.303 回答
0

您是否正在寻找这样的东西:

location / {
    try_files $uri.html $uri/index.html =404;
}

基本上这将a.html首先尝试文件,如果失败,它将尝试index.html最后显示一个404. 另外请记住restart nginx在编辑vhost文件后。

于 2012-12-21T06:24:15.733 回答