[英]Handling 404's with Named Location in Nginx and returning custom 404's
我有一个网络服务,它通过 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?
最近遇到了来自命名位置的自定义错误问题,并偶然发现了这个问题。
我认为这里发生的事情是,当您回复 404 时, fastcgi_intercept_errors on
拦截它,并且您定义了error_page 404
,这可能会导致潜在的递归。 在这种情况下,nginx 将返回其内部错误。
我认为您不应该使用fastcgi_intercept_errors
,或者您可以在 @imageHandlers 位置定义不同的自定义错误,例如未使用的错误( error_page 417 /some_file.html
),这样您就不再继承从该位置外部定义的 error_page 。
在我的例子中,我必须添加一个recursive_error_pages on;
也,你可能也需要它,不确定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.