萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

LNMP 系列教程五:Nginx 配置自定義 404 錯誤頁面

背景

LNMP 一鍵安裝包預設不配置 404 頁面,直接顯示 Nginx 內建錯誤頁,體驗差且洩露伺服器資訊。需手動配置自定義 404 頁面。

三步驟配置

1. 開啟 FastCGI 錯誤攔截

編輯 /usr/local/nginx/conf/nginx.conf,在 http 區塊添加:

fastcgi_intercept_errors on;
nginx.conf http 區塊配置

2. 站點配置指定 404 頁面

編輯虛擬主機配置 /usr/local/nginx/conf/vhost/yourdomain.com.conf,在 server 區塊添加:

error_page 404 = /404.html;

並確保網站根目錄下存在 404.html 檔案。

3. 重載 LNMP 生效

/root/lnmp restart

驗證配置語法

/usr/local/nginx/sbin/nginx -t
# 輸出應為:
# the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
# configuration file /usr/local/nginx/conf/nginx.conf test is successful

進階:動態 404 頁面 (PHP 處理)

error_page 404 = /404.php;
# 404.php 可記錄 Referer、User-Agent、請求 URI 寫入日誌或資料庫,便於 SEO 分析死鏈

常見問題

  • fastcgi_intercept_errors off (預設) 時,PHP 返回 404 狀態碼但 Nginx 不攔截,顯示 PHP 程式輸出內容而非自定義頁面
  • 權限問題:404.html 需 Nginx 執行用戶 (通常 www) 可讀
  • 多站點需分別在各 vhost 配置檔設定
copyright © 萬盛學電腦網 all rights reserved