2009-06-21 156 views
43

Nginx + PHP(在fastCGI上)對我很好。當我輸入一個不存在的PHP文件的路徑時,我只是得到一個「沒有指定輸入文件」,而不是獲得默認的404錯誤頁面(對於任何無效的.html文件)。Nginx - 自定義404頁面

我如何定製這個404錯誤頁面?

回答

33

您可以使用nginx config中的error_page屬性。

例如,如果你打算到404錯誤頁面設置爲/404.html,使用

error_page 404 /404.html; 

500錯誤頁面設置爲/500.html是一樣簡單:

error_page 500 /500.html; 
+2

雖然鏈接是OK和答案微創作品,未經環節,它可以受益於更多的闡述。 – Paul 2015-08-10 00:38:50

+0

@Paul I 100%對此表示贊同,因此我在此答案中添加了一些代碼示例;-) – 2015-10-18 14:32:56

101

你可以設置nginx.conf中每個位置塊的自定義錯誤頁面,或整個網站的全局錯誤頁面。

重定向到一個簡單的404頁面未找到某個具體位置:

location /my_blog { 
    error_page 404 /blog_article_not_found.html; 
} 

站點寬404頁:

server { 
    listen 80; 
    error_page 404 /website_page_not_found.html; 
    ... 

您可以附加標準錯誤代碼在一起有一個單頁對於幾種類型的錯誤:

location /my_blog { 
    error_page 500 502 503 504 /server_error.html 
} 

要重定向到一個完全不同的服務器, g您必須在您的HTTP部分定義爲上游服務器名爲server2:

upstream server2 { 
    server 10.0.0.1:80; 
} 
server { 
    location /my_blog { 
     error_page 404 @try_server2; 
    } 
    location @try_server2 { 
     proxy_pass http://server2; 
    } 

manual可以給你更多的細節,也可以搜索谷歌的條款nginx.conf和error_page在網絡上的真實例子。

+1

您是否知道是否可以使用錯誤通配符?像`error_page 50 * = /error_50x.html;`? – 2012-11-27 01:58:23

+0

不允許使用通配符 - 此服務器命令的wiki頁面在這裏http://wiki.nginx.org/NginxHttpCoreModule#error_page - 也不是必需的,因爲錯誤代碼是由不改變的HTTP協議定義的常常。請參閱http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html或http://en.wikipedia.org/wiki/List_of_HTTP_status_codes查看完整列表,如果您認爲那裏有任何數字,我想可以添加任何數字將是未來需要的代碼。 – 2012-11-27 17:17:49

27

「error_page」參數不夠。

最簡單的解決方法是

server{ 
    root /var/www/html; 
    location ~ \.php { 
     if (!-f $document_root/$fastcgi_script_name){ 
      return 404; 
     } 
     fastcgi_pass 127.0.0.1:9000; 
     include fastcgi_params.default; 
     fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name; 
    } 

順便說一句,如果你想Nginx的處理由PHP腳本返回404種狀態,你需要在添加

fastcgi_intercept_errors;

例如,

location ~ \.php { 
     #... 
     error_page 404 404.html; 
     fastcgi_intercept_errors on; 
    } 
14

不再推薦使用這些答案,因爲try_files工作速度比在這方面if。只需在你的PHP所在地塊添加try_files測試文件是否存在,否則返回一個404

location ~ \.php { 
    try_files $uri =404; 
    ... 
}