以下 These 問題在 #nginx IRC 頻道天天有人問。把這些反模式改掉,效能與安全都會明顯改善。
永遠不要使用 777。逐層檢查目錄權限:
namei -om /path/to/check
反例是在每個 location 重複寫 root;正確做法是在 server 區塊宣告一次,location 只留自己的規則。
server {
server_name www.example.com;
root /var/www/nginx-default/;
location / { }
location /foo { }
location /bar { }
}
把 index index.php index.htm index.html; 放在 http 層即可,server 與 location 無須再寫一遍。
請參閱 If Is Evil。絕大多數情境都有更好的替代方案。
# 反例
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 寫死。
location / { try_files $uri $uri/ /index.html; }
它會依序測試 $uri → $uri/ → index.html,簡潔且避開 if。
try_files $uri $uri/ /index.php?q=$uri&$args;
參數名依套件而異:Drupal 用 q,Joomla、WordPress 用 page;有些軟體直接讀 REQUEST_URI,可簡化為 try_files $uri $uri/ /index.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;
}
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
rewrite ^ https://example.com$request_uri? permanent; # 更好 return 301 https://example.com$request_uri;
用內建變數 $request_uri 可省掉多餘的捕獲與比對。
rewrite ^ https://example.com permanent;
server {
root /var/www/site;
location / { try_files $uri $uri/ @proxy; }
location @proxy { fastcgi_pass unix:/tmp/phpcgi.socket; }
}
靜態資源(圖片、CSS、JS)直接由 nginx 送出,省下的開銷非常可觀。
多半是瀏覽器快取。Firefox 按 Ctrl+Shift+Delete 清掉 Cache;或直接用 curl 驗證。
sendfile off;
未明確開啟 underscores_in_headers on; 時,nginx 會靜默丟棄含底線的標頭,這是為了避免標頭對映到 CGI 變數時產生歧義。
把 root 設成 /,一次 /etc/passwd 請求就可能洩漏整台機器的帳號資訊,若 worker 還以 root 執行,等於把主機雙手奉上。內容請放在 /var/www/、/srv 或 /usr/share/www。
套件升級時預設目錄內容常被覆蓋,重要檔案請自立門戶。
upstream { server 10.48.41.12; }
server { listen 127.0.0.16:80; }
主機名若在開機或重啟時無法解析,nginx 會綁定失敗而無法啟動。
因 POODLE 漏洞,只保留 TLS:
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;