加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > Nginx > 正文

在/ nginx中将/foo.html重定向到/ foo但不是/ to / index

发布时间:2020-12-13 21:36:59 所属栏目:Nginx 来源:网络整理
导读:我在磁盘上的文件有扩展名:index.html,a.html.我想要http://example.com/a请求加载/var/www/a.html和http://example.com/加载/var/www/index.html.我希望其他网址重定向到规范网址,因此http://example.com/a.html应重定向到http://example.com/a. 我的配置

我在磁盘上的文件有扩展名:index.html,a.html.我想要http://example.com/a请求加载/var/www/a.html和http://example.com/加载/var/www/index.html.我希望其他网址重定向到规范网址,因此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

但它发送/到/索引:

$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.html重定向到/ a,但也会停止发送/ to / 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扩展名,url中没有索引)制作nginx吗?

最佳答案
我认为你的重写规则可能会倒退.也许只是这个(没有重写规则):

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读