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

我已经读了十几个rewite问题。 大多数问题都是.php,但是我有简单的.html文件,所以关于=> about.html。但是我不能得到nginx这样做:

  • 接受有或没有“/”的url
  • 将domain.com/about和domain.com/about/redirect到domain.com/about.html
  • 添加尾部的斜杠到URL,所以如果我写的domain.com/about写它的domain.com/about/

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

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

我试过这也给出了一个500错误:

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

我试图从这里build议转换apache到nginx(winginx.com)没有成功。

此代码不起作用。 我正在尝试redirect并添加尾部斜线:

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

任何build议都会让我开心。

我已经测试了这个配置,它似乎符合您的要求(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; }