Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

Nginx 常見陷阱與錯誤配置整理

以下 These 問題在 #nginx IRC 頻道天天有人問。把這些反模式改掉,效能與安全都會明顯改善。

1. 權限

永遠不要使用 777。逐層檢查目錄權限:

namei -om /path/to/check

2. root 應寫在 server 層

反例是在每個 location 重複寫 root;正確做法是在 server 區塊宣告一次,location 只留自己的規則。

server {
    server_name www.example.com;
    root /var/www/nginx-default/;
    location / { }
    location /foo { }
    location /bar { }
}

3. index 不必到處重複

把 index index.php index.htm index.html; 放在 http 層即可,server 與 location 無須再寫一遍。

4. if 是邪惡的

請參閱 If Is Evil。絕大多數情境都有更好的替代方案。

5. 別用 if 判斷 Host

# 反例
if ($host ~* ^www\.(.+)) { set $raw_domain $1; rewrite ^/(.*)$ $raw_domain/$1 permanent; }

# 正解
server { server_name www.example.com; return 301 $scheme://example.com$request_uri; }
server { server_name example.com; }

可讀性更好、開銷更低,也避免把 http/https 寫死。

6. 判斷檔案存在用 try_files

location / { try_files $uri $uri/ /index.html; }

它會依序測試 $uri → $uri/ → index.html,簡潔且避開 if。

7. 框架的入口配置

try_files $uri $uri/ /index.php?q=$uri&$args;

參數名依套件而異:Drupal 用 q,Joomla、WordPress 用 page;有些軟體直接讀 REQUEST_URI,可簡化為 try_files $uri $uri/ /index.php;。

8. 不要把不受控的請求丟給 PHP

location ~* \.php$ 把所有 .php 結尾請求轉給 FastCGI,會被 cgi.fix_pathinfo 的猜測行為利用,導致任意檔案被當成 PHP 執行。防禦方式:

# 於 php.ini
cgi.fix_pathinfo=0

# 只放行特定檔案
location ~* (file_a|file_b|file_c)\.php$ { fastcgi_pass backend; }

# 上傳目錄禁止執行
location /uploaddir { location ~ \.php$ { return 403; } }

# try_files 過濾
location ~* \.php$ { try_files $uri =404; fastcgi_pass backend; }

# 巢狀位置過濾
location ~* \.php$ {
    location ~ \..*/.*\.php$ { return 404; }
    fastcgi_pass backend;
}

9. SCRIPT_FILENAME 用變數

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

10. 精簡 rewrite

rewrite ^ https://example.com$request_uri? permanent;
# 更好
return 301 https://example.com$request_uri;

用內建變數 $request_uri 可省掉多餘的捕獲與比對。

11. rewrite 別漏掉 scheme

rewrite ^ https://example.com permanent;

12. 不要把所有請求都 proxy 給 PHP

server {
    root /var/www/site;
    location / { try_files $uri $uri/ @proxy; }
    location @proxy { fastcgi_pass unix:/tmp/phpcgi.socket; }
}

靜態資源(圖片、CSS、JS)直接由 nginx 送出,省下的開銷非常可觀。

13. 改設定卻沒生效

多半是瀏覽器快取。Firefox 按 Ctrl+Shift+Delete 清掉 Cache;或直接用 curl 驗證。

14. VirtualBox 下的 sendfile 問題

sendfile off;

15. 帶底線的 HTTP 標頭消失

未明確開啟 underscores_in_headers on; 時,nginx 會靜默丟棄含底線的標頭,這是為了避免標頭對映到 CGI 變數時產生歧義。

16. 不要用 / 或 /root 當網站根目錄

把 root 設成 /,一次 /etc/passwd 請求就可能洩漏整台機器的帳號資訊,若 worker 還以 root 執行,等於把主機雙手奉上。內容請放在 /var/www/、/srv 或 /usr/share/www。

17. 不要用預設文件根目錄放正式資料

套件升級時預設目錄內容常被覆蓋,重要檔案請自立門戶。

18. listen 與 upstream 避免寫主機名

upstream { server 10.48.41.12; }
server { listen 127.0.0.16:80; }

主機名若在開機或重啟時無法解析,nginx 會綁定失敗而無法啟動。

19. HTTPS 停用 SSLv3

因 POODLE 漏洞,只保留 TLS:

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
Copyright © Linux教程網 All Rights Reserved