nginx - 将 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 时它会下载一个文件。任何人都可以帮助我吗?谢谢!!
解决方案
我认为您的正则表达式已损坏,其作者的意思是^(.*)\?.*$
并希望保留没有查询字符串的 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;
}
推荐阅读
- reactjs - 错误:需要一个赋值或函数调用,而是看到一个表达式 no-unused-expressions。如何解决?
- javascript - 数据表未激活
- laravel - Laravel 与 4 表的关系
- cassandra - 拥有一个带有单行分区的 Cassandra 表是一种不好的做法吗?
- html - 在我添加文本时背景图像与导航栏的距离,我该怎么做?
- powerapps - 如何从 Excel 表格中提取相关数据,在 PowerApps 中创建下拉列表并构建编辑表单?
- python - Python Selenium 单击没有任何标签/名称/等的按钮
- spring - org.springframework.beans.factory.NoSuchBeanDefinitionException:没有符合条件的 bean 类型
- javascript - 打开新窗口时如何保持新窗口的滚动位置?
- python - ctypes malloc 用于图像数据