部署 DedeCMS 等靜態化生成系統時,常遇到「生成靜態頁面後,欄目頁面全部 403 Forbidden」。經排查,**並非權限問題,而是 Nginx `index` 指令配置缺失 `index.html`** 導致。本文詳細分析 403 成因、排查步驟、修正配置與預防清單。
# 原錯誤配置
server {
listen 80;
server_name domain.com;
root /var/www/html;
index index.php; # <=== 只有 index.php,缺少 index.html / index.htm
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
流程:
server {
listen 80;
server_name domain.com;
root /var/www/html;
# 關鍵修正:按優先序列出所有可能的索引文件
index index.html index.htm index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# ... PHP 處理同上
}
重載:`nginx -s reload` 即時生效。
| 成因 | 檢查方法 | 解決 |
|---|---|---|
| 文件/目錄權限錯誤 | `ls -l` 確認 Nginx 用戶 (www-data/nginx) 可讀 | `chown -R www-data:www-data /var/www/html`、`chmod -R 755` 目錄、`644` 文件 |
| root 路徑錯誤 | 確認 `root` 指向正確目錄 | 修正 `root` 指令 |
| location 匹配順序錯誤 | 靜態文件 location 被 PHP location 搶先 | 調整 location 順序,`location ~ \.php$` 放後 |
| autoindex off (預設) | 請求目錄且無 index 文件 | 添加 index 文件、或特定目錄 `autoindex on` |
| SELinux/AppArmor 限制 | `ausearch -m avc` / `aa-status` | 調整安全策略或標籤 `chcon -Rt httpd_sys_content_t` |
| fastcgi 權限 | PHP-FPM 用戶無法讀取腳本 | 統一 PHP-FPM 與 Nginx 用戶組 |
更多 Nginx 進階:`try_files` 進階用法、FastCGI 快取優化、SSL/TLS 配置最佳實踐、限流限速 (limit_req/limit_conn)、反向代理負載均衡、日誌分析與 GoAccess 視覺化、Docker 化 Nginx 部署、OpenResty Lua 動態路由,請參考本站專題系列。