我正在尝试添加一个带有别名指令的新位置块,该指令基于动态 URI 以访问不同的 API。现在我可以手动添加每个位置块,但想知道是否可以使用 REGEX 来映射它。
问题是它返回了 404 错误。我在服务器上的不同文件夹中运行 laravel 子应用程序。
有什么线索吗?
**
手动工作
location /api/product {
alias /path/to/api/product/public;
try_files $uri $uri/ @rewrite;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
}
}
location @rewrite {
rewrite /api/product/(.*)$ /api/product/index.php?/$1 last;
}
Run Code Online (Sandbox Code Playgroud)
错误 404 / 未指定输入文件
location ~ /api/(.*) {
alias /path/to/api/$1/public;
try_files $uri $uri/ @rewrite;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
}
}
location @rewrite {
rewrite /api/(.*)/(.*)$ /api/$1/index.php?/$2 last;
}
Run Code Online (Sandbox Code Playgroud)
更多测试
一种
URL: app.tdl/api/tweets
Result: 'Index of /api/tweets/'
Output of $request_filename: /home/vagrant/code/Gateway/modules/tweets/app
location /api/tweets {
alias /home/vagrant/code/Gateway/modules/tweets/app;
autoindex on;
}
Run Code Online (Sandbox Code Playgroud)
乙
URL: app.tdl/api/tweets
Result: Nginx's 404
Output of $apiName: tweets
Output of $request_filename: /home/vagrant/code/Gateway/modules/tweets/app
location ~ "/api/(?<apiName>[^/]+)" {
alias "/home/vagrant/code/Gateway/modules/$apiName/app" ;
autoindex on;
}
Run Code Online (Sandbox Code Playgroud)
alias在正则表达式中 location需要捕获文件的完整路径。有关详细信息,请参阅文档。
此外,您现有的捕获过于贪婪。
由于这个长期存在的问题,您可能会遇到使用try_fileswith 的问题,您可能想用块替换它。aliasif
例如:
location ~ ^/api/(?<product>[^/]+)/(?<filename>.*)$ {
alias /path/to/api/$product/public/$filename;
if (!-e $request_filename) {
rewrite ^ /api/$product/index.php?/$filename last;
}
location ~ \.php$ {
if (!-f $request_filename) { return 404; }
...
}
}
Run Code Online (Sandbox Code Playgroud)
正则表达式 location块按顺序计算。该块需要放置在任何冲突的正则表达式 location块之上,例如块级别的另一个location ~ \.php$块server。
第二个if块是避免将不受控制的请求传递给 PHP。见这种谨慎的使用if。
| 归档时间: |
|
| 查看次数: |
2342 次 |
| 最近记录: |