萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Nginx 安全加固:隱藏版本號防止資訊洩露的完整步驟

為什麼要隱藏版本號?

默認情況下 Nginx 在 HTTP 響應頭 `Server` 與錯誤頁面底部暴露版本 (如 `nginx/1.18.0`)。攻擊者可針對已知版本漏洞 (CVE) 發起精準攻擊。隱藏版本號屬於**資訊隱藏**策略,屬纵深防御基礎環節。

驗證當前洩露情況

$ curl -I https://localhost
HTTP/1.1 200 OK
Server: nginx/1.18.0   # 版本號暴露
...

步驟 1:修改 nginx.conf 關閉 server_tokens

# vim /etc/nginx/nginx.conf
http {
    ...
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 60;
    tcp_nodelay on;
    server_tokens off;   # 新增此行,建議放在 http 塊內
    ...
}

步驟 2:修改 FastCGI 配置隱藏 PHP 端版本

編輯 fastcgi.conf 或 fastcgi_params (視發行版而定):

# 找到
fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;
# 改為
fastcgi_param SERVER_SOFTWARE nginx;

步驟 3:重新加載配置生效

# nginx -t          # 語法檢查
# systemctl reload nginx
# 或
# /etc/init.d/nginx reload

驗證效果

$ curl -I https://localhost
HTTP/1.1 200 OK
Server: nginx        # 僅顯示 nginx,無版本號
...

404/50x 錯誤頁面底部也不再顯示版本資訊。

進階:完全自定義 Server 頭

需編譯安裝時使用 --with-http_headers_more_module 或第三方模組 ngx_headers_more:

more_set_headers 'Server: MyWebServer';

總結

兩行配置修改即可消除版本號洩露,成本極低、收益明顯。建議納入基線檢查清單,定期掃描確認生效。

copyright © 萬盛學電腦網 all rights reserved