2011-04-08 208 views
10

我學會了如何讓NGINX返回503客戶錯誤頁面, 但我不能找出如何做到以下幾點:如何在NGINX中設置自定義503錯誤頁面?

示例配置文件:

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

    error_page 503 /503.html; 
    location = /503.html { 
     root www; 
    } 

正如你所看到的,根據上面的代碼中,如果在我的根目錄中找到一個名爲503.html的頁面,則該站點會將此頁面返回給用戶。

看來,雖然上面的代碼工作,當有人簡單地訪問我的網站鍵入

它沒有陷阱的請求,如:

通過我的代碼,用戶仍然可以看到除index.php以外的任何其他頁面。

問題:

我如何陷阱請求在我的網站的所有網頁,並將其轉發給503.html每當503.html存在於我的根文件夾?

回答

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; 
    } 

} 

更多信息:

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

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

+0

try_files是最好的做法。此外,它不會丟失。它只是不完整。 – ASPiRE 2011-04-09 19:49:30

+0

@Vini沒有失蹤和不完整之間的區別是什麼,對我來說它是一樣的。我更新了示例以包含try_files而不是if -f。希望有所幫助。 – 2011-04-09 21:32:27

+0

謝謝Ken。順便說一句,$ uri做什麼?我連續兩次看到它。 – ASPiRE 2011-04-10 02:40:58

5

下面的配置適用於接近最新的穩定nginx的1.2.4。 我找不到使用if啓用維護頁面的方法,但顯然根據IfIsEvil這是一個好的if

  • 啓用維護touch /srv/sites/blah/public/maintenance.enable。您可以rm禁用該文件。
  • 錯誤502將映射到503這是大多數人想要的。你不想給Google一個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; 
    } 
} 
+0

謝謝你。如果不使用'if',我也找不到方法。很高興看到這是一個可以接受的使用! – 2013-09-18 16:32:41

3

其他的答案都是正確的,但我想補充的是,如果你使用內部代理你還需要在你的代理服務器的一個補充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; 
    }