``` server { listen 80; server_name www.test.com; root /var/www/test; index index.html index.htm;
location / { }
#定義錯(cuò)誤頁(yè)面碼,如果出現(xiàn)相應(yīng)的錯(cuò)誤頁(yè)面碼,轉(zhuǎn)發(fā)到指定頁(yè)面。 error_page 404 403 500 502 503 504 /404.html;
#承接上面的location。 location = /404.html { #錯(cuò)誤頁(yè)面的目錄路徑。 root /usr/share/nginx/html; } } ```
第二種方法是使用Nginx反向代理的錯(cuò)誤頁(yè)面處理。使用此方法時(shí),需要進(jìn)行以下配置:
``` upstream www { server 192.168.1.201:7777 weight=20 max_fails=2 fail_timeout=30s; ip_hash; }
server { listen 80; server_name www.test.com; root /var/www/test; index index.html index.htm;
location / { if ($request_uri ~* ^/$) { rewrite .* http://www.test.com/index.html redirect; }
#關(guān)鍵參數(shù):當(dāng)后端返回404,nginx攔截錯(cuò)誤并定義相應(yīng)錯(cuò)誤頁(yè)面。 proxy_intercept_errors on; proxy_pass http://www; proxy_set_header HOST $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-FOR $proxy_add_x_forwarded_for; }
error_page 404 /404.html;
location = /404.html { root /usr/share/nginx/html; } } ```
第三種方法是針對(duì)Nginx解析PHP代碼的錯(cuò)誤頁(yè)面處理。使用此方法時(shí),需要在http段中加一個(gè)變量`fastcgi_intercept_errors on`。然后可以通過(guò)以下方式指定錯(cuò)誤頁(yè)面:
``` error_page 404 /404.html;
location = /404.html { root /usr/share/nginx/html; }
或
error_page 404 /404.html;
error_page 404 = http://www.test.com/error.html; ```
通過(guò)上述三種方法,我們可以輕松地進(jìn)行Nginx錯(cuò)誤頁(yè)面處理,使得用戶獲得更好的訪問(wèn)體驗(yàn)。