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

时间:2017-01-12 16:44:43

标签: .htaccess nginx url-rewriting

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

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

我尝试过这段代码 rewrite ^/([a-zA-Z0-9]+)$ /$1.html; 但是它在以" /"结尾的网址上给出了404错误。也尝试了这个 rewrite ^([a-zA-Z0-9]+)/?$ $1.html有同样的错误。

有人建议我应该使用try try_files

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

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

我尝试将apache从建议here转换为nginx(winginx.com)但没有成功。

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

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

任何建议都会让我感到高兴。

2 个答案:

答案 0 :(得分:2)

我测试了这个配置,它似乎符合您的要求(YMMV):

root /path/to/root;

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

第一个位置尝试按原样提供文件 ,这是资源文件所必需的。否则它会延迟到指定的位置。

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

有关详细信息,请参阅this documentthis document

答案 1 :(得分:0)

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

location /about {
    try_files about.html;
}