如何在NGINX中设置自定义503错误页面?

ASP*_*iRE 12 nginx

我学会了如何让NGINX返回503客户错误页面,但我无法了解如何执行以下操作:

示例配置文件:

    location / {
        root   www;
        index  index.php;
        try_files /503.html =503;
    }

    error_page 503 /503.html;
    location = /503.html {
        root   www;
    }
Run Code Online (Sandbox Code Playgroud)

如您所见,根据上面的代码,如果503.html在我的根目录中找到一个被调用的页面,该站点将把该页面返回给用户.

似乎虽然上面的代码可以在有人只是访问我的网站时输入

它不会捕获如下请求:

使用我的代码,用户仍然可以看到配置文件页面或其他任何页面index.php.

问题:

我如何陷阱请求所有页面在我的网站,并转发给503.html503.html出现在我的根文件夹是什么?

Ada*_*ent 7

以下配置适用于接近最新的稳定nginx 1.2.4.我找不到一种方法来启用维护页面if而不使用但显然根据IfIsEvil它是好的if.

  • 启用维护touch /srv/sites/blah/public/maintenance.enable.您可以rm禁用该文件.
  • 错误502将映射到503大多数人想要的内容.你不想给谷歌502.
  • 自定义502503页面.您的应用将生成其他错误页面.

网上还有其他配置,但它们似乎不适用于最新的nginx.

server {
    listen       80;
    server_name blah.com;

    access_log  /srv/sites/blah/logs/access.log;
    error_log  /srv/sites/blah/logs/error.log;

    root   /srv/sites/blah/public/;
    index  index.html;

    location / {
        if (-f $document_root/maintenance.enable) {
            return 503;
        }
        try_files /override.html @tomcat;
    }

    location = /502.html {
    }

    location @maintenance {
       rewrite ^(.*)$ /maintenance.html break;
    }

    error_page 503 @maintenance;
    error_page 502 =503 /502.html;

    location @tomcat {
         client_max_body_size 50M;

         proxy_set_header  X-Real-IP  $remote_addr;
         proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header  Host $http_host;
         proxy_set_header  Referer $http_referer;
         proxy_set_header  X-Forwarded-Proto http;
         proxy_pass http://tomcat;
         proxy_redirect off;
    }
}
Run Code Online (Sandbox Code Playgroud)


Ken*_*ane 6

更新:将"if -f"更改为"try_files".

试试这个:

server {
    listen      80;
    server_name mysite.com;
    root    /var/www/mysite.com/;

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

        # When maintenance ends, just mv maintenance.html from $root
        ... # the rest of your config goes here
     }

    location @maintenance {
      return 503;
    }

}
Run Code Online (Sandbox Code Playgroud)

更多信息:

https://serverfault.com/questions/18994/nginx-best-practices

http://wiki.nginx.org/HttpCoreModule#try_files

  • 这为/maintenance.html提供了状态代码200.如何以503的正确状态提供页面? (26认同)
  • 如果你有一个文件 `/maintenance.html`,这将永远不会返回 `503` http 代码,因为 `try_files` 指令会在那里停止。 (3认同)

Lay*_*yke 6

其他答案都是正确的,但要补充的是,如果您使用内部代理,则还需要proxy_intercept_errors on;在其中一个代理服务器上添加。

所以例如...

    proxy_intercept_errors on;
    root /var/www/site.com/public;
    error_page 503 @503;
    location @503 {
       rewrite ^(.*)$ /scripts/503.html break;
    }
Run Code Online (Sandbox Code Playgroud)