【问题标题】:Nginx locations and nested Slim indexesNginx 位置和嵌套的 Slim 索引
【发布时间】:2023-04-04 20:52:01
【问题描述】:

使用php Slim框架,结构如下:

/root
    /dir_parent_1/
        /dir_child_1
            /index.php
    /dir_parent_2
        /index.php

/root/dir_parent_1/dir_child_1/index.phpusers 路由,并且 /root/dir_parent_2/index.phpclients 路由。

我如何编写 Nginx 位置以匹配两种可能的组合?

我试试:

location ~ ^/root/(\w+)
{
    try_files $uri /gestionhospitales/api/$1/index.php?$query_string;
}

location ~ ^/root/(\w+)/(\w+)
{
    try_files $uri /gestionhospitales/api/$1/$2/index.php?$query_string;
}

但它们是相互排斥的。去“/root/dir_parent_1/dir_child_1/users”匹配第一个规则(因为它是第一个。如果我颠倒顺序,则匹配第二个),

我也开始为这两种情况编写规则,但我不知道如何完成它:

location ~ ^/root/(\w+)?/(\w*)
{
    try_files $uri /gestionhospitales/api/$1/$2/index.php?$query_string;
#  tried with if, rewrite, etc. But i'm not nginx expert.
}

提前致谢。

【问题讨论】:

  • Nginx 优先位置不依赖于顺序,它首先选择声明位置中的最长路径,阅读docs并更新问题跨度>

标签: php nginx slim


【解决方案1】:

您必须设置的唯一途径是将所有内容转发到公共目录中的 index.php 文件。

root         /path/www.mysite.com/public_html;

try_files $uri /index.php;

此文件应包含用于 boostrap Slim 框架的 php 代码。然后所有“路由”将由 PHP 和 Slim 根据您在 index.php 中的代码而不是 nginx 处理。

$app->get('/users', function () {
    echo "This is the user route!";
});

$app->get('/clients', function () {
    echo "This is the client route!";
});

你可以在官方文档中看到一个完整的例子here

【讨论】:

  • 看来这是正确的方法。我想分离索引以避免需要不必要的文件,但这是我将在不久的将来实施的一种早期优化。非常感谢。
猜你喜欢
  • 2016-04-22
  • 1970-01-01
  • 2014-01-09
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
相关资源
最近更新 更多