You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx如何配置用户自定义404不存在时fallback到系统默认404

Nginx自定义404回退配置解决方案

核心修改逻辑

原配置缺少「用户自定义404.html不存在时回退到平台默认提示」的判断逻辑,只需要调整@not_found命名位置的规则,增加对用户目录下404.html存在性的校验,不存在就跳转到预置的@my404即可。

调整后的完整配置

# 原有map规则保持不变
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;
        # 先尝试读取当前用户目录下的自定义404.html,不存在则跳转到平台默认404
        try_files /404.html @my404;
    }

    location @my404 {
        internal;
        # 可根据需要修改default_type指定返回格式,比如改为text/html
        default_type text/plain;
        return 404 "Page not found.";
    }
}

生效校验

修改配置后先执行nginx -t校验语法正确性,确认无报错后执行systemctl reload nginx重载配置即可生效。

内容的提问来源于stack exchange,提问作者mlen108

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 01:06:04