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

Nginx正则Location-A返回404时如何降级到Location-B?

修正Nginx降级配置实现404自动 fallback

原配置无法触发降级的核心原因是未开启后端错误状态码拦截,Nginx默认会直接将后端返回的404传递给客户端,不会执行error_page定义的跳转逻辑。

修正后的完整配置

# location-A:匹配无扩展名的图片请求,忽略日期路径
location ~ ^\/images\/([0-9\-]+)\/([0-9a-zA-Z\-_]+) {
    add_header Cache-Control "public, max-age=2592000";
    proxy_intercept_errors on; # 关键新增:开启拦截后端返回的错误状态码
    error_page 404 = @fallback;
    proxy_pass https://subdomain.example.com/images/$2;
}

# location-B:404时的降级处理逻辑
location @fallback {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

关键修改说明

  • proxy_intercept_errors on;:启用该指令后,Nginx会拦截后端服务器返回的HTTP错误状态码(如404),转而执行error_page配置的处理流程,这是实现降级跳转的核心前提。
  • 其余配置保持原有逻辑不变:依然忽略请求路径中的日期部分,将请求转发到子域名的对应资源;fallback位置保持WebSocket兼容的代理配置。

验证方式

当https://subdomain.example.com/images/abc返回404时,Nginx会自动将请求转发到http://localhost:3000处理,实现预期的降级逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:27:24