nginx 不支持子文件夹 error_page 指令

时间:2020-12-22 13:50:45

标签: nginx

我正在尝试使我的非常简单的 nginx 提供静态文件以进行回退,或者如果是 404 或 50x 错误,则显示错误页面,如下所示:

server {
  listen 80;
  server_name frontend;
  add_header X-Frame-Options "SAMEORIGIN";

  error_page 404 = @fallback404;
  location @fallback404 {
    index index.html;
    root /usr/share/nginx/html/404-error;
    internal;
  }

  error_page 500 502 503 504 @fallback5xx;
  location @fallback5xx {
    index index.html;
    root /usr/share/nginx/html/5xx-errors;
  }

  location /testing500 {
    fastcgi_pass unix:/does/not/exist;
  }

  location / {
    autoindex off;
    index index.html;
    root /usr/share/nginx/html;
    try_files $uri $uri/ =404;
  }
}

即使 /testing/500 返回计划 nginx 的 404 页面:

enter image description here

我还尝试将 error_page 指令声明为它们各自的子文件夹的位置,其中存在错误的实际 index.html,在我的情况下:/404-error/index.html/5xx-errors/index.html 不使用 {{1 }} 定义,效果是一样的。

我错过了什么? nginx 不尊重子文件夹中的错误页面或其他内容吗?

1 个答案:

答案 0 :(得分:0)

您需要在 try_files 块中添加一个 location @fallback404 语句以选择要返回的正确 URI。

例如:

error_page 404 = @fallback404;
location @fallback404 {
    root /usr/share/nginx/html/404-error;
    try_files /index.html =404;
    internal;
}

但是,更简单的解决方案是在 error_page 语句本身中指定 URI。

例如:

error_page 404 /404-error/index.html;
location = /404-error/index.html {
    root /usr/share/nginx/html;
    internal;
}