Nginx 维护页面,最佳实践

Nginx 维护页面,最佳实践

我想配置服务器以在存在维护页面时显示它。我尝试了此代码并成功运行:

location / {
    try_files /maintenance.html $uri $uri/ @codeigniter;
}

但我注意到它会返回 200 状态代码,这可能会让搜索引擎感到困惑。我认为最佳做法是返回 503 状态代码。我在谷歌上找到了几个相关页面,比如。但是,他们使用 if 进行重定向,而根据 nginx 文档,使用 ifs 并不安全。

有没有不使用 if 的方法?在这种情况下使用 if 安全吗?

谢谢。

答案1

我认为最佳做法是返回 500 状态代码。

我认为您的意思是 503 而不是 500。

它们用于if进行重定向,并且根据 nginx 文档,使用 ifs 并不安全。

return不。只有100%安全在上下文iflocation

根据nginx 文档,您可以指定 HTTP 状态代码作为 的最后一个参数try_files。我试过了,但是没用。

答案2

这是我所做的。

            if (-f $document_root/maintenance.html) {
                    return 503;
            }
            error_page 503 @maintenance;
            location @maintenance {
                    rewrite ^(.*)$ /maintenance.html break;
            }

如果文件存在,则会显示维护页面。删除文件后,您将恢复正常。

答案3

这个配置对我有用:

server {
  server_name _;
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  location ~* \.(css|png|js|jpg|jpeg|ico) {
      root /static/maintenance;
  }
  error_page 503 @maintenance;
  location @maintenance {
    root /static/maintenance;
    rewrite ^(.*)$ /index.html break;
  }
  location / {
    return 503;
  }
}

它对每个请求返回/static/maintenance/index.html代码为 503 的文件。

它不会通过重定向改变 URL。

类似资源

  • /static/maintenance/main.css
  • /static/maintenance/favicon.ico
  • ETC。

可使用代码 200。

答案4

如果维护页面只有 HTML

没有资产文件(CSS、JS、...)

location = @maintenance {
    root html/;
    # `break`: use this `location` block
    rewrite ^ "/maintenance.html" break;
}

location / {
    error_page 503 @maintenance;
    return 503;

    # ...
}

对于具有资产文件(CSS / JS / ...)的维护页面

其流程如下:

  • 如果 URI/return 503
    • 内部重定向至/maintenance.html
  • 如果在maintenance目录中找到 URI(针对资产),则返回状态为 200 的文件
  • 所有其他请求,重定向至/
# for handle maintenance web page
server {
    listen unix:/var/run/maintenance.nginx.sock;

    # for Windows
    # listen 8000;
    
    location @index {
        # use redirect because if URI has sub-folder ($uri == /path/path/),
        # the relative path for asset file (CSS, JS, ...) will be incorrect
        rewrite ^ / redirect;
    }

    location = / {
        # maintenance page URI
        error_page 503 /maintenance.html;

        return 503;
    }

    # use RegExp because it has higher priority
    location / {
        root html/maintenance/;

        # redirect all URI to index (503) page (except asset URI),
        # asset URI still return status 200
        try_files $uri @index;
    }
}

# original server block
server {
    listen 80;
    location / {
        proxy_pass http://unix:/var/run/maintenance.nginx.sock:;

        # for Windows
        # proxy_pass http://127.0.0.1:8000;
    }

    # ...
}
  • 维护时,maintenance.conf您可以将配置放入其中。include maintenance.conf

  • 我不会使用,if (-f <file>)因为它会尝试检查每个请求的文件是否存在

如果你需要绕过某些 IP 地址

更多详情这里

参考:Nginx 维护

相关内容