Nginx 重写规则子文件夹 404 错误

Nginx 重写规则子文件夹 404 错误

我不知道如何使用 Nginx 重写规则设置我的 index.php 文件以使其像下面的示例一样工作。

如果我访问该网址,它会给出 404 错误,未找到 instad echo 'hello'。

网址:

http://www.example.com/directory/sub-directory/

给定 URL 中的 /sub-directory/ 实际上不是 /directory/ 内的真实目录。如果我访问该 URL,我会收到 404 错误 - 这确实没问题,但 /sub-directory/ 是友好 URL(没有查询 ?argument=value)。

/sub-directory/ 不是固定值(在下面的例子中是固定值),它可以是 /sub-directory-new/ - 取决于。

那么,对于 URL 中 /directory/ 之后的 /value/ 内的任何值,如果我访问这种 URL,怎样才能不出现 404 错误?

/directory/ 中的 Index.php:

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$wanted = "sub-directory";

$tokens = explode('/', $actual_link);
$result =  $tokens[sizeof($tokens)-2]; // result is "sub-directory"
if($wanted == $result) {
    echo "hello";
}

Nginx的:

location /directory {
    try_files $uri $uri/ /directory/$uri;
    error_page 404 =200 /directory
}

我是否应该为规则添加一些参数,例如:location /directory$1?如果是,添加哪一个参数以及如何使其工作?

有人有什么想法吗?

感谢您的分享和信息!

答案1

在 nginx 中实现友好 URL 的通常方式如下:

location /directory {
    try_files $uri $uri/ @rewrites;
}

location @rewrites {
    rewrite ^ /directory/index.php;
}

此配置假定您的root指令指向所在的目录/directory

因此,nginx 首先会尝试文件或目录是否存在于实际文件系统中。如果文件不存在,则它会将请求转发到您的 PHP 文件。当然,您需要在 nginx 中正确配置您的 PHP 处理块。

相关内容