Apache HTTP Server 是全球最流行的 Web 伺服器之一。本文以 Apache 2.2.x 為例,記錄在 Windows 平台上的安裝流程、關鍵配置項與虛擬目錄/虛擬主機設定要點,供快速部署參考。正式環境請務必閱讀官方文檔。
Apache 2.x.x-win32-x86-no_ssl.msiApache 2.x.x-win32-x86-openssl-x.x.x.msiApache安裝目錄/conf/httpd.confListen 80 改為未用埠(如 Listen 81)https://localhost,出現預設頁面即成功。預設 Apache 以 Local System 帳戶運行,權限過高。建議:
apache_svc),僅授予必要權限。httpd.conf 詳解配置文件位於 安裝目錄/conf/httpd.conf,修改後請用「開始功能表 → Apache HTTP Server 2.2 → Test Configuration」驗證語法。
DocumentRoot "D:/Programs/Apache2.2/htdocs"
使用正斜線 /,避免 Windows 反斜線轉義問題。
# 帶尾斜線:訪問 https://localhost/webpath/ 映射到 D:/Programs/WebPath
Alias /webpath/ "D:/Programs/WebPath"
# 不帶尾斜線:訪問 https://localhost/webpath 也會自動補齊重導向
Alias /webpath "D:/Programs/WebPath"
權限配置必加(否則 403 Forbidden):
<Directory "D:/Programs/WebPath">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted # Apache 2.4+ 語法;2.2 用 Order allow,deny / Allow from all
</Directory>
# 永久重導向 (301)
Redirect permanent /foo/ https://www.example.com/bar/
# httpd.conf 末尾啟用
Include conf/extra/httpd-vhosts.conf
conf/extra/httpd-vhosts.conf 範例:
NameVirtualHost *:80
<VirtualHost *:80>
ServerAdmin admin@example.com
DocumentRoot "D:/Web/site1"
ServerName site1.local
ServerAlias www.site1.local
ErrorLog "logs/site1-error.log"
CustomLog "logs/site1-access.log" common
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "D:/Web/site2"
ServerName site2.local
</VirtualHost>
同時修改 C:\Windows\System32\drivers\etc\hosts 加入:
127.0.0.1 site1.local www.site1.local site2.local
| 現象 | 排查方向 |
|---|---|
| 啟動失敗 | 執行 httpd -t 檢查語法;查看 logs/error.log |
| 403 Forbidden | 目錄權限 Require all granted、路徑拼寫、Alias 大小寫 |
| 404 Not Found | DocumentRoot/Alias 路徑是否存在、重導向規則衝突 |
| PHP 不解析 | 載入 php7_module、AddHandler application/x-httpd-php .php、DirectoryIndex index.php |
httpd -t 語法通過https://localhost 顯示預設頁https://localhost/webpath/ 可訪問虛擬目錄https://site1.local 正確解析https://localhost 憑證有效Windows 上部署 Apache 2.2 核心在於:正確選擇安裝包、解決埠衝突、配置 httpd.conf 與 httpd-vhosts.conf、並給予虛擬目錄恰當的 <Directory> 權限。養成「改配置 → Test Configuration → 重啟服務 → 查 error.log」的閉環習慣,能解決 90% 以上的部署問題。