【问题标题】:Handling 404's with Named Location in Nginx and returning custom 404's在 Nginx 中处理具有命名位置的 404 并返回自定义 404
【发布时间】: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


    【解决方案1】:

    最近遇到了来自指定位置的自定义错误问题,偶然发现了这个问题。

    我认为这里发生的情况是,当您回复 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;,你可能还需要它,不确定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-19
      • 2015-10-04
      • 2018-04-01
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多