【问题标题】:convert htaccess rule to nginx server block将 htaccess 规则转换为 nginx 服务器块
【发布时间】:2021-07-12 21:36:22
【问题描述】:

我在主根文件夹内的文件夹 /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 时它会下载一个文件。任何人都可以帮助我吗?谢谢!!

【问题讨论】:

    标签: nginx mod-rewrite url-rewriting


    【解决方案1】:

    我认为您的正则表达式已损坏,其作者的意思是 ^(.*)\?.*$ 并希望保留没有查询字符串的 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;
    }
    

    【讨论】:

    • 嘿,Ivan,尝试了提供的两种配置,但没有使用。据我所知,该 URL 的主要思想是例如: https:something.com/rest-api/hello-world 将其转换为 https:/something.com/rest-api/index.php?hello-world .感谢您的支持!
    • @DavidM。你能检查一下更新的版本吗?
    猜你喜欢
    • 1970-01-01
    • 2015-02-17
    • 2017-07-15
    • 2015-09-09
    • 1970-01-01
    • 2014-11-07
    • 2018-09-01
    • 1970-01-01
    相关资源
    最近更新 更多