nginx重写HTML文件并添加尾部斜杠



我读过十几个问题。大多数问题都是针对.php但我有简单的.html文件,所以关于=>关于.html。但我无法让nginx这样做:

  • 接受带或不带"/"的网址
  • 将 domain.com/about 和 domain.com/about/重定向到 domain.com/about.html
  • 在 URL 中添加尾部斜杠,这样如果我写 domain.com/about 它会写 domain.com/about/

我已经尝试过使用此代码 rewrite ^/([a-zA-Z0-9]+)$ /$1.html;但它在以"/"结尾的 URL 上给了我 404 错误。也试过这个 rewrite ^([a-zA-Z0-9]+)/?$ $1.html具有相同的错误。

有人建议我应该使用尝试try_files

我也尝试了这个,它给出了 500 错误:

location / { 
rewrite ^(.*)$ /%1 redirect; 
rewrite ^/([^.]+)$ /$1.html break; 
}

我试图从这里的建议将 apache 转换为 nginx (winginx.com),但没有成功。

此代码不起作用。我正在尝试重定向并添加尾部斜杠:

if (!-e $request_filename){
rewrite ^/(.*)/$ /$1 redirect;
}
if (!-e $request_filename){
rewrite ^/(.*[^/])$ /$1/ redirect;
}

任何建议都会让我高兴。

我已经测试了此配置,它似乎满足您的要求(YMMV):

root /path/to/root;
location / {
    try_files $uri @rewrite;
}
location @rewrite {
    rewrite ^(.*[^/])$ $1/ permanent;
    rewrite ^(.*)/$ $1.html break;
}

第一个位置尝试按原样提供资源文件所需的文件。否则,它将遵从命名位置。

命名位置将永久重定向任何不以 / 结尾的 URI。否则,将提供.html文件。

有关详细信息,请参阅此文档和此文档。

我认为在这里使用try_files是合适的。例如:

location /about {
    try_files about.html;
}

最新更新