虛擬主機技術允許單一實體伺服器(或叢集)同時運行多個獨立網站,各擁有獨立的文件根目錄、域名、日誌、設定。Apache 支援兩種主要模式:基於 IP 與 基於域名。
每個網站擁有獨立 IP 位址。適用於需 SSL/TLS 獨立憑證(早期 SNI 不普及時)、嚴格隔離安全需求的場景。
# httpd.conf 範例
Listen 192.168.1.10:80
DocumentRoot "/www/site1"
ServerName site1.com
ErrorLog logs/site1-error.log
CustomLog logs/site1-access.log common
# 第二個實例需獨立設定檔、獨立啟動腳本
Listen 80
DocumentRoot "/www/site1"
ServerName site1.com
ErrorLog logs/site1-error.log
CustomLog logs/site1-access.log common
DocumentRoot "/www/site2"
ServerName site2.org
ErrorLog logs/site2-error.log
CustomLog logs/site2-access.log common
同一 IP 可綁定多 Port(如 80、8080),對應不同 DocumentRoot。
單一 IP 透過 HTTP Host 標頭區分網站。節省 IP 成本、設定彈性、現代瀏覽器全支援。
NameVirtualHost *:80(Apache 2.4+ 可省略)。<VirtualHost *:80> 設定 ServerName 與 DocumentRoot。Listen 80
NameVirtualHost *:80
ServerName www.site1.com
ServerAlias site1.com *.site1.com
DocumentRoot "/www/site1"
ErrorLog logs/site1-error.log
CustomLog logs/site1-access.log common
ServerName www.site2.org
DocumentRoot "/www/site2"
ErrorLog logs/site2-error.log
CustomLog logs/site2-access.log common
# 預設虛擬主機(無匹配 ServerName 時落入此處)
ServerName default
DocumentRoot "/www/default"
# * 匹配所有 IP,IP 變更無需改設定
ServerName www.example.com
DocumentRoot "/www/example"
Listen 443
ServerName secure.site1.com
SSLEngine on
SSLCertificateFile /etc/ssl/site1.crt
SSLCertificateKeyFile /etc/ssl/site1.key
DocumentRoot "/www/site1-secure"
ErrorLog "|/usr/sbin/rotatelogs /var/log/apache2/site1-error.%Y%m%d.log 86400"
CustomLog "|/usr/sbin/rotatelogs /var/log/apache2/site1-access.%Y%m%d.log 86400" combined
Options -Indexes 禁用目錄瀏覽。AllowOverride None 禁止 .htaccess(效能更好),改用主設定檔。<LimitExcept GET POST> Require all denied </LimitExcept>。mod_security WAF。mod_deflate / mod_brotli 壓縮傳輸。ExpiresActive On、ExpiresByType 靜態資源快取。MPM Event 替代 Prefork,搭配 PHP-FPM。| 現象 | 可能原因 | 解決 |
|---|---|---|
| 所有域名指向同一站點 | 缺少 NameVirtualHost 或 ServerName 拼錯 | 檢查拼寫、啟用 NameVirtualHost |
| 403 Forbidden | DocumentRoot 權限不足、SELinux 阻擋 | chmod 755、setsebool -P httpd_read_user_content 1 |
| SSL 憑證錯誤 | SNI 不支援、憑證域名不符 | 確認客戶端支援 SNI、使用 SAN 憑證 |
| 重啟失敗 | 語法錯誤、Port 衝突 | apachectl configtest、netstat -tlnp | grep :80 |
基於域名的虛擬主機是現代標準做法,配合 SNI 解決 HTTPS 多憑證問題。善用 ServerAlias、預設虛擬主機、日誌分離、安全強化與效能優化設定,即可在單一伺服器穩定運行數十上百個獨立站點。