繁体   English   中英

基于正则表达式的NGINX别名路径

[英]NGINX Alias path based on regex

我正在尝试使用基于动态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;
}

错误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;
}

更多测试

一种

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;
}

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;
}

正则表达式 location alias需要捕获文件的完整路径。 有关详细信息,请参见文档

另外,您现有的捕获内容过于贪婪。

由于这个长期存在的问题 ,将try_filesalias一起使用可能会遇到问题,您可能希望将其替换为if块。

例如:

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; }
        ...
    }
}

正则表达式 location块按顺序求值。 该块需要放置在任何有冲突的正则表达式 location块之上,例如server块级别的另一个location ~ \\.php$块。

第二个if块是避免将不受控制的请求传递给PHP 请参阅有关使用if 注意事项

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM