【问题标题】:render custom 404 in nginx or something else if 404 doesn't exist如果 404 不存在,则在 nginx 或其他内容中呈现自定义 404
【发布时间】:2021-10-11 10:48:45
【问题描述】:

我想托管用户上传的 HTML 文件,如果他们提供了自定义 404,我需要显示它,否则显示我自己的 404。

示例工作流程:

  1. 访问者尝试访问 example.com/pages/page1.html
  2. pages/page1.html 不存在但 $user 已上传 404.html 所以显示它
  3. $user 没有提供404.html 所以自己显示简单的消息

到目前为止,我已经介绍了第 1 步和第 2 步,但无法为最后一步制定逻辑。

我的 /simplified/ 配置:

# each user has their own storage path etc
# just to illustrate
map $host $user {
    dog.example.com             group/1/2/3;
    cat.example.com             group/4/5/1;
    dog-want-cookie.example.com group/9/9/9;
}

server {
    listen 8000;
    server_name ~^(?<vhost>[^.]*)\.example\.com$;

    root /sites/$user;

    location / {        
        try_files $uri $uri/index.html @not_found;
    }

    location @not_found {
        internal;
        error_page 404 /404.html;
    }
}

不确定在哪里为我自己的错误“页面”“调用”配置。

location @my404 {
    return 404 "Page not found.";
}

我在 Debian 上使用 Nginx 1.19.3。

【问题讨论】:

  • 你是打算自己写404.html还是使用Nginx默认的404响应作为后备?
  • 我想使用我自己的 404 作为后备。最好通过简单地返回带有消息的错误(绕过模板查找/渲染)来实现这一点,如上面的location @my404

标签: nginx configuration


【解决方案1】:

使用error_page 而不是try_files 调用指定位置。详情请见this document

例如:

error_page 404 @not_found;

location / {        
    try_files $uri $uri/index.html =404;
}

使用try_files 测试404.html 文件是否存在。

例如:

location @not_found {
    try_files /404.html /fallback404.html =404;
}

您无需将命名位置标记为internal,因为它们无法被外部访问。

在上面的示例中,fallback404.html 文件位于同一文档根目录中。 =404 是语法所必需的,但永远不会到达,因为第二个文件始终存在。详情请见this document


要在不同的文档根目录中使用备用404.html 文件,您可以级联两个命名位置。

例如:

location @not_found {
    try_files /404.html @fallback;
}
location @fallback {
    root /path/to/fallback/files;
    try_files /404.html =404;
}

或者,您可以将@fallback 位置的内容替换为您的return 语句。

例如:

location @fallback {
    return 404 "Page not found.";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 2010-11-04
    • 2018-07-02
    • 2022-10-02
    • 1970-01-01
    相关资源
    最近更新 更多