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

NGINX配置维护页面时资源返回503,静态资源无法正常访问

NGINX维护页面配置修复方案

问题现象

配置维护页面后,当maintenance.enable文件存在时:

  • 维护页面的CSS文件被当作HTML文档渲染
  • 图片资源无法访问,请求返回503错误

原配置代码

location ^~/maintenance/ {
   root /path/to/the/maintenance/maintenance.html;
}
set $maintenance 0;
if (-f /path/to/the/maintenance/maintenance.enable) {
   set $maintenance 1;
}
if ($maintenance = 1) {   
root /path/to/the/maintenance/maintenance.html
rewrite ^/(.*) /maintenance/maintenance.html break;
}

配置错误分析

  1. root路径设置错误:root指令需要指向资源所在的目录,而非具体文件。原配置中把root设为HTML文件路径,导致NGINX无法正确解析静态资源的实际位置。
  2. 全局重写覆盖静态资源请求:rewrite ^/(.*) /maintenance/maintenance.html break;会将所有请求(包括CSS、图片等静态资源)都重写到维护页面,导致静态资源无法正常加载,返回503错误。

修正后的配置

# 处理维护页面的静态资源请求
location ^~/maintenance/ {
    root /path/to/the; # 指向包含maintenance目录的上级目录
    expires 10m; # 可选:设置静态资源缓存时间
}

set $maintenance 0;
if (-f /path/to/the/maintenance/maintenance.enable) {
    set $maintenance 1;
}

# 维护模式开启时,仅重写非维护资源的请求
if ($maintenance = 1) {
    root /path/to/the;
    if ($request_uri !~ ^/maintenance/) {
        return 503;
    }
}

# 自定义503响应页面
error_page 503 @maintenance;
location @maintenance {
    rewrite ^(.*)$ /maintenance/maintenance.html break;
}

关键修正点说明

  • 静态资源路径修正:将location ^~/maintenance/中的root改为/path/to/the,这样请求/maintenance/css/style.css会对应到实际文件路径/path/to/the/maintenance/css/style.css,NGINX能正确返回静态资源。
  • 避免全局重写:通过$request_uri !~ ^/maintenance/判断,只对非维护目录的请求返回503,维护目录下的CSS、图片等资源不受影响,可正常加载。
  • 规范HTTP状态码:使用return 503而非直接重写,符合维护模式的HTTP规范,同时通过error_page 503 @maintenance指定自定义响应页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:50:33