使用try_files并使用默认的前控制器文件在NGINX位置块内重写

问题描述 投票:0回答:1

我正在从旧框架迁移到php中的新框架。旧框架的每个URL都有一个登录页面,例如:

  1. test.com/page1将被路由到public_directory/page1.php

  2. test.com/another_page将被路由到public_directory/another_page.php

以下块用于这些请求:

location / { 
    limit_req zone=globallimit burst=20 nodelay;
    try_files $uri $uri/ @php; 
}

location @php {         
    rewrite ^(/[^/]+)$ $1.php last;
    rewrite ^(/[^/]+)/(.*)$ $1.php?q=$2 last;
}

新框架使用前端控制器,每个请求都必须定向到public_directory/front_controller.php。迁移时,我们将删除旧的着陆文件,这是我们可以识别哪些页面使用新框架的方法。

@php块之后,我向front_controller.php添加了默认参数,这是我想的工作。

location / { 
    limit_req zone=globallimit burst=20 nodelay;
    try_files $uri $uri/ @php /front_controller.php?$arg; 
}

location @php {         
    rewrite ^(/[^/]+)$ $1.php last;
    rewrite ^(/[^/]+)/(.*)$ $1.php?q=$2 last;
}

如果@php重写块与文件不匹配,则默认为/front_controller.php?arg;但是,我发现的是现在@php被忽略了,而nginx却直接进入了front_controller.php。我要去哪里错了,为什么现在忽略@php重写?

nginx nginx-config
1个回答
0
投票

try_files指令需要一个文件列表,后跟URI /命名位置/ HTTP错误代码,如果列表中没有文件,则将使用该错误代码。假设您的站点根目录为/home/user/www,而您的请求为http://example.com/some/path,则此配置检查以下文件/目录是否存在:

  1. /home/user/www/some/path文件,如果找到该文件,其内容将在响应正文中返回。
  2. /home/user/www/some/path/目录,如果此目录存在,将检查是否存在用index指令定义的所有可能的索引文件,将使用第一个找到的文件。如果在此目录中未找到索引文件,则如果您具有autoindex on;或HTTP 403 Forbidden,则nginx返回目录内容。
  3. /home/user/www@php文件。显然,找不到此文件。

如果所有这些检查均未成功,则nginx将遵循定义为最后一个参数(在这种情况下为/front_controller.php?$arg的URI(或命名位置)。

您可以做的是尝试类似的事情

location ~ ^(/[^/]+)$ {
    try_files $1.php /front_controller.php?$arg;
}
location ~ ^(?<script>/[^/]+)/(?<param>.*)$ {
    rewrite ^ $script?q=$param last;
}
© www.soinside.com 2019 - 2024. All rights reserved.