将 htaccess 文件转换为子文件夹的 nginx try_file

Convert htaccess file to nginx try_file for subfolder

  RewriteEngine On
  RewriteRule ^([^\.]+)$ .html [NC,L]

如何将 apache .htaccess 文件转换为 nginx try_file?

我在以下文件夹结构中有静态 html 文件,并以漂亮的 URL 风格访问它们,没有 .html 扩展,它正在与 apache 一起工作,但是当我尝试转换 nginx配置它为子文件夹抛出 404。我使用 https://winginx.com/en/htaccess 网站进行转换。

# nginx configuration

location / {
  rewrite ^/([^\.]+)$ /.html break;
}
+ root-folder  
  + index.html  - url - www.hello.com
  + abc.html  - url - www.hello.com/abc
  + .........   
  + xyz.html  - url - www.hello.com/xyz  
  + category-folder   
     + category1.html  - url - www.hello.com/category-folder/category1
     + category2.html  - url - www.hello.com/category-folder/category2
     + category3.html  - url - www.hello.com/category-folder/category3
  + page-folder 
     + page1.html - url - www.hello.com/page-folder/page1
     + page2.html - url - www.hello.com/page-folder/page2
     + page3.html - url - www.hello.com/page-folder/page3

任何帮助都将非常有用。

try_files 对于由 PHP 或其他语言提供支持的动态框架的前端控制器模式来说是一个很好的指令,其中您只有一个 bootstrap 文件,例如/index.php,其中 "serves" SEO 友好 URL:

/foo/ -> /index.php
/bar/ -> /index.php
/lorem/ipsum -> /index.php

如果您的文件是静态的并且您事先知道文件结构,try_files 除了 stat(文件存在性检查)系统调用的性能损失外,什么也没有。

例如从 Richard 的评论中应用 try_files $uri $uri.html $uri/ =404;,意味着对于 URI /category-folder/category1,NGINX 首先检查实际文件 /category-folder/category1 是否存在,然后检查 /category-folder/category1.html 是否存在,以防万一不存在,请检查 /category-folder/category1/ 目录是否存在。

坚持 rewrite 很有意义,在这种情况下,转换配置非常简单。它将导致 1:1 匹配它在 Apache 中的工作方式。

使用我的 "fairly sophisticated" Apache to NGINX config converter,它会检测何时需要使用 try_files,何时不需要,您将获得所需的重写(将其直接放在 server 上下文,不在 location):

rewrite ^/([^\.]+)$ /.html last;

要检查此重写,您可以使用 this test

如您所见,唯一的技巧是 NGINX 重写中的 URI(以及通常在 NGINX 中指定的 URI)必须以斜杠开头,而在 Apache 中它们被省略。