[英]NGINX Alias path based on regex
I'm trying to add a new location block with an alias directive that are based on a dynamic URI to access different APIs. 我正在尝试使用基于动态URI的别名指令添加一个新的位置块来访问不同的API。 Right now I can do this manually adding each location block but was wondering if it could be mapped by using REGEX. 现在,我可以手动添加每个位置块,但是想知道是否可以使用REGEX映射它。
The problem is that it's returning a 404 error. 问题是它返回404错误。 I'm running a laravel sub app in a different folder on my server. 我正在服务器上其他文件夹中运行laravel子应用程序。
Any clues? 有什么线索吗?
** **
WORKING MANUALLY 手动工作
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;
}
ERROR 404 / No input file specified 错误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;
}
MORE TESTS 更多测试
A 一种
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;
}
B 乙
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;
}
alias
inside a regular expression location
requires the full path to the file to be captured. 正则表达式 location
alias
需要捕获文件的完整路径。 See the documentation for details. 有关详细信息,请参见文档 。
Also, your existing capture is too greedy. 另外,您现有的捕获内容过于贪婪。
You may encounter problems using try_files
with alias
due to this long standing issue , you may want to replace it with an if
block. 由于这个长期存在的问题 ,将try_files
与alias
一起使用可能会遇到问题,您可能希望将其替换为if
块。
For example: 例如:
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; }
...
}
}
Regular expression location
blocks are evaluated in order. 正则表达式 location
块按顺序求值。 This block needs to be placed above any conflicting regular expression location
block, such as another location ~ \\.php$
block at the server
block level. 该块需要放置在任何有冲突的正则表达式 location
块之上,例如server
块级别的另一个location ~ \\.php$
块。
The second if
block is to avoid passing uncontrolled requests to PHP . 第二个if
块是避免将不受控制的请求传递给PHP 。 See this caution on the use of if
. 请参阅有关使用if
注意事项 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.