首页 > 解决方案 > 将 htaccess 规则转换为 nginx 服务器块

问题描述

我在主根文件夹内的文件夹 /rest-api 的 .htaccess 文件中有以下代码。

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ /rest-api/index.php?__route__=/$1 [L,QSA]

所以,我需要将它迁移到 nginx 服务器块中,我正在尝试一些选项,但没有任何效果。我发现的最佳方法是:

location /rest-api {
   if (!-e $request_filename){
      rewrite ^/(.*)\?*$ /index.php?__route__=/$1;
   }
}

但是当它应该转换 url 时它会下载一个文件。任何人都可以帮助我吗?谢谢!!

标签: nginxmod-rewriteurl-rewriting

解决方案


我认为您的正则表达式已损坏,其作者的意思是^(.*)\?.*$并希望保留没有查询字符串的 URI 部分。NGINX 使用没有查询字符串部分的规范化 URI,所以你可以试试这个:

location /rest-api {
    try_files $uri $uri/ /rest-api/index.php?__route__=$uri&$args;
}

上述配置的唯一警告是,&如果 HTTP 请求根本没有任何查询参数,它会传递一个额外的。一般来说它不应该导致任何麻烦,但如果是这样,一些更准确的配置版本是

location /rest-api {
    set $qsa '';
    if ($args) {
        set $qsa '&';
    }
    try_files $uri $uri/ /rest-api/index.php?__route__=$uri$qsa$args;
}

更新

我对 Apache mod_rewrite 不是很熟悉,但是如果您需要使用不带/rest-api前缀的 URI 部分作为__route__查询参数,请尝试以下操作:

location = /rest-api {
    # /rest-api to /rest-api/ redirect is for safety of the next location block
    rewrite ^ /rest-api/ permanent;
}
location /rest-api/ {
    set $qsa '';
    if ($args) { set $qsa $args; }
    rewrite ^/rest-api(.*)$ $1 break;
    try_files /rest-api$uri /rest-api$uri/ /rest-api/index.php?__route__=$uri$qsa$args;
}

推荐阅读