萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

隱藏 Apache 與 PHP 版本資訊:伺服器安全加固指南

前言

預設下 Apache 與 PHP 會在 HTTP 回應標頭與錯誤頁面洩露版本資訊,攻擊者可據此鎖定已知漏洞進行攻擊。本文說明如何徹底隱藏版本資訊,提升伺服器安全性。

隱藏 Apache 版本資訊

核心設定指令

# httpd.conf 或 apache2.conf
ServerTokens Prod
ServerSignature Off

ServerTokens 等級對照

設定值回應標頭範例資訊洩露程度
Full (預設)Server: Apache/2.4.57 (Ubuntu) PHP/8.2.1 OpenSSL/3.0.2❌ 完整版本+模組
OSServer: Apache/2.4.57 (Ubuntu)⚠️ 版本+作業系統
MinimalServer: Apache/2.4.57⚠️ 僅版本號
MinorServer: Apache/2.4⚠️ 主次版本
MajorServer: Apache/2⚠️ 主版本
Prod / ProductOnlyServer: Apache✅ **最少資訊**

ServerSignature 設定

  • Off:錯誤頁面不顯示伺服器資訊(推薦)
  • On:顯示伺服器版本與虛擬主機名稱
  • EMail:顯示版本+管理員 Email(`ServerAdmin` 指令)

隱藏 PHP 版本資訊

php.ini 設定

; php.ini
expose_php = Off

效果對比

設定X-Powered-By 標頭錯誤頁面 PHP 版本
expose_php = On (預設)X-Powered-By: PHP/8.2.1顯示
expose_php = Off(無此標頭)隱藏

進階:移除/偽裝 Server 標頭 (mod_headers)

需載入 `mod_headers` 模組:

# httpd.conf
LoadModule headers_module modules/mod_headers.so

# 隱藏或偽裝 Server 標頭
Header always unset Server
Header always set Server "MyWebServer/1.0"

# 也可移除 X-Powered-By(雙重保險)
Header always unset X-Powered-By

驗證設定生效

命令列檢查

$ curl -I https://example.com/
HTTP/1.1 200 OK
Server: Apache
Content-Type: text/html; charset=UTF-8
# 無 X-Powered-By
# 無詳細版本號

線上工具檢查

  • SecurityHeaders.com
  • Observatory by Mozilla
  • SSL Labs Server Test

完整安全標頭建議

# httpd.conf 或 .htaccess (需 AllowOverride Headers)
# 隱藏版本
ServerTokens Prod
ServerSignature Off
Header always unset X-Powered-By

# 安全標頭
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';"
Header always set Permissions-Policy "geolocation=(), microphone=()"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" env=HTTPS

Nginx + PHP-FPM 環境設定

# nginx.conf
server {
    # 隱藏 Nginx 版本
    server_tokens off;
    
    # 隱藏 PHP 版本 (fastcgi 傳遞)
    fastcgi_hide_header X-Powered-By;
    
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

# php.ini (同樣需要)
expose_php = Off

錯誤頁面客製化

避免預設錯誤頁洩露路徑、資料庫錯誤等敏感資訊:

# httpd.conf
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html
ErrorDocument 502 /errors/502.html
ErrorDocument 503 /errors/503.html

# 自訂錯誤頁面範例 (errors/500.html)


服務暫時不可用

    

500 - 內部伺服器錯誤

我們已記錄此錯誤,技術團隊正在處理中。

返回首頁

檢核清單

  • ✅ Apache: `ServerTokens Prod`
  • ✅ Apache: `ServerSignature Off`
  • ✅ PHP: `expose_php = Off`
  • ✅ 移除/偽裝 `Server` 標頭 (mod_headers)
  • ✅ 移除 `X-Powered-By` 標頭
  • ✅ 設定安全標頭 (CSP, HSTS, X-Frame-Options 等)
  • ✅ 客製化錯誤頁面
  • ✅ 定期掃描確認無資訊洩露

注意事項

隱藏版本資訊屬於「深度防禦」的一環,非萬靈丹。核心防護仍是:及時修補漏洞、最小權限原則、WAF、入侵偵測、定期滲透測試。

copyright © 萬盛學電腦網 all rights reserved