我在.htaccess文件中有以下代码,用于主根文件夹中的文件夹/rest-api。
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;
}
更新
我不太熟悉Apach 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;
}