【发布时间】:2019-09-13 11:49:26
【问题描述】:
我有一个通过 Nginx 网络服务器提供动态图像的网络服务。
通过解释 URL 结构并将初始 404 响应传递给命名位置来处理请求,然后将 URL 与各种条件进行匹配以返回适当的图像。
这是基本配置:
error_page 404 = @imageHandlers;
location @imageHandlers {
#= Match pattern 1 =========
if ($uri ~* "^/(some_pattern1)$") {
set $x = $1;
rewrite .* "image_handler_type1.php?q=$x" last;
}
#= Match pattern 2 =========
if ($uri ~* "^/(some_pattern2)$") {
set $x = $1;
rewrite .* "image_handler_type2.php?q=$x" last;
}
etc....
}
这很好用,但我还想在不匹配任何模式时显示自定义 404 错误页面。
我认为我可以在“custom_error.php”文件中处理这个问题:
<?php
$status = $_GET["status"];
if ($status == 404) {
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
}
?>
<html>
<head><title><?php echo $status;?></title></head>
<body bgcolor="white">
<center><h1>Error <?php echo $status;?></h1></center>
</body>
</html>
所以 Nginx 配置现在看起来像这样:
fastcgi_intercept_errors on;
error_page 404 = @imageHandlers;
location @imageHandlers {
#= Match pattern 1 =========
if ($uri ~* "^/(some_pattern1)$") {
set $x = $1;
rewrite .* "image_handler_type1.php?q=$x" last;
}
#= Match pattern 2 =========
if ($uri ~* "^/(some_pattern2)$") {
set $x = $1;
rewrite .* "image_handler_type2.php?q=$x" last;
}
etc....
#= Otherwise display custom 404 =========
rewrite .* "/custom_error.php?status=404" last;
}
我添加了“fastcgi_intercept_errors on”,以便 Nginx 不会拦截大于 300 的响应代码。
不幸的是,“custom_error.php”返回的 404 响应仍然被 Nginx 拦截并返回它自己的标准 404 响应,因为我猜,“@imageHandlers”命名位置传递将初始 404 重置为状态 200块。
如果我从“custom_error.php”中注释掉“if ($status == 404)”块,自定义错误显示正常但我得到不正确的状态 200 状态响应代码。
如何使用我已经设置的配置实现自定义 404?
【问题讨论】:
标签: php nginx error-handling url-rewriting