Apache HTTP Server (httpd) 仍是全球市佔率最高的 Web 伺服器。以 Red Hat 系 (RHEL/CentOS/AlmaLinux/Rocky) 為例,完整部署指南:
httpd-2.4.57-5.el9 等。| 方式 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 套件管理器 (dnf/yum/apt) | 依賴自動解析、安全更新一鍵、SELinux 政策整合 | 版本較舊、編譯選項固定 | 標準生產環境、合規要求 |
| 原始碼編譯 | 最新版本、自訂 MPM/模組、最佳化編譯參數 (-march=native) | 手動管理更新、需自行處理 systemd/SELinux/Logrotate | 高效能需求、特殊模組、容器映像建構 |
/etc/httpd/
├── conf/
│ ├── httpd.conf # 主設定檔
│ └── magic
├── conf.d/ # 模組/虛擬主機片段 (IncludeOptional conf.d/*.conf)
│ ├── ssl.conf
│ ├── php.conf
│ ├── vhost-*.conf
│ └── ...
├── modules/ # .so 動態模組
├── logs/ -> /var/log/httpd/
└── run/ -> /run/httpd/
| MPM | 特性 | 適用場景 | 關鍵參數 (httpd.conf / conf.d/mpm.conf) |
|---|---|---|---|
| prefork | 單執行緒多進程、相容非執行緒安全模組 (mod_php) | 舊版 PHP、非執行緒安全應用 | StartServers, MinSpareServers, MaxSpareServers, MaxRequestWorkers (≤ RAM / 單進程記憶體) |
| worker | 多執行緒多進程、較省記憶體 | 一般動態內容、Proxy 後端 | ThreadsPerChild, MaxRequestWorkers, ServerLimit |
| event (預設 2.4+) | 非同步事件驅動、Keep-Alive 釋放執行緒、最高併發 | 現代 Web、高併發、HTTP/2、反向代理 | ThreadsPerChild, MaxRequestWorkers, ServerLimit, AsyncRequestWorkerFactor |
記憶體估算:ps -ylC httpd --sort:rss 觀察 RSS,單進程約 20~40 MB (event) / 40~80 MB (prefork+mod_php)。
MaxRequestWorkers = (Total RAM - OS/DB 保留) / 單進程 RSS。
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com
ErrorLog logs/example.com-error_log
CustomLog logs/example.com-access_log combined
# 導向 HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
</VirtualHost>
<VirtualHost *:443>
ServerName example.com
DocumentRoot /var/www/example.com
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/example.com.crt
SSLCertificateKeyFile /etc/pki/tls/private/example.com.key
SSLCertificateChainFile /etc/pki/tls/certs/ca-bundle.crt
# TLS 1.2/1.3 only
SSLProtocol -all +TLSv1.2 +TLSv1.3
SSLCipherSuite HIGH:!aNULL:!MD5:!3DES
# HSTS
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
</VirtualHost>
mod_security (WAF) + OWASP CRS 3.4+ 規則集mod_evasive / mod_ratelimit 防暴力/DoSmod_headers 設定 CSP、X-Frame-Options、Referrer-Policymod_ssl OCSP Stapling、Session Cachemod_http2 啟用 HTTP/2 (需 TLS 1.2+)mod_proxy + mod_proxy_fcgi 連接 PHP-FPM / Java / Go 後端# ab (ApacheBench)
ab -n 10000 -c 200 -k https://example.com/
# wrk (現代、支援 HTTP/2)
wrk -t4 -c200 -d30s --latency https://example.com/
# h2load (HTTP/2 專用)
h2load -n 10000 -c 200 -m 10 https://example.com/
關鍵指標:RPS、P50/P95/P99 延遲、錯誤率、CPU/記憶體/網路飽和度。調整 MPM 參數後重測,找到甜蜜點。
/etc/logrotate.d/httpd
/var/log/httpd/*log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 640 root adm
sharedscripts
postrotate
/bin/systemctl reload httpd > /dev/null 2>&1 || true
endscript
}
掌握上述架構,Apache 部署、調校、維運即有完整框架。