使用 nginx 重写“隐藏”.html 文件扩展名

Dou*_*hen 17 rewrite nginx

我正在通过 nginx 提供一个静态站点,我的目标是替换如下所示的 URL:

http://foo.com/bar.html

http://foo.com/bar

关键是没有尾部斜杠。我目前正在使用位置别名做类似的事情,但这很乏味,因为它需要每个文件的位置块,并且它还附加一个斜杠,因为 nginx 将别名视为目录:

    location / {
        root    /srv/www/foo/public_html;
        index   index.html;
    }

    location /bar1 {
        alias /srv/www/foo/public_html/;
        index bar1.html;
    }

    location /bar2 {
        alias /srv/www/foo/public_html/;
        index bar2.html;
    }
Run Code Online (Sandbox Code Playgroud)

等等。我已经通读了有关重写的文档,但似乎无法将所说的内容与我需要做的事情综合起来。我不是来自 Apache 背景;nginx 是我第一次涉足网络服务器,所以我确定我错过了一些明显的东西,因为我的 HTTP 背景很弱。在此先感谢您提供的任何帮助。

Sha*_*den 18

try_files 应该是你想要的。

像这样的东西:

try_files $uri.html $uri $uri/ =404;
Run Code Online (Sandbox Code Playgroud)

  • 将其更改为 `try_files $uri.html $uri/ =404;` 会更好的 SEO 明智,因为你不会有两个 url *http://foobar.com/bar* 和 *http://foobar.com /bar.html* 指向相同的资源。 (5认同)

Bry*_*yce 6

根据@Khaja 的评论,最佳答案是:

try_files $uri.html $uri/ =404;
Run Code Online (Sandbox Code Playgroud)

这样只提供一份资源副本(没有 .html 扩展名)。您不想将链接强度划分为提供重复内容的多个 URL。在此处查找文档。