單一 Apache 伺服器透過「虛擬主機」機制,即可依網域名稱或埠號提供多個獨立網站服務。本文說明以獨立設定檔管理多站點的最佳實務,包含建立站點目錄、撰寫虛擬主機設定、註冊 Windows 服務、驗證與常見坑點。
httpd.conf,監聽 80 埠,DocumentRoot 指向主要網站目錄。web2.conf),監聽不同埠 (如 8080) 或同埠不同網域 (Name-based),DocumentRoot 指向另一目錄。D:\www\web1 # 主站點
D:\www\web2 # 第二站點
確保 Apache 服務帳號 (通常是 Local System 或指定服務帳號) 對此兩目錄有讀取/執行權限。
# 找到 DocumentRoot 與對應 區塊
DocumentRoot "D:/www/web1"
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
重啟 Apache 服務驗證:瀏覽 https://localhost 應顯示 web1 內容。
複製 httpd.conf 為 web2.conf,修改三處關鍵設定:
Listen 8080 # 原為 80,改為不同埠
ServerName localhost:8080 # 對應埠號
DocumentRoot "D:/www/web2" # 指向第二站點目錄
# 同步修改對應的 區塊權限
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
# 為避免衝突,建議另行指定錯誤/存取日誌
ErrorLog "logs/web2_error.log"
CustomLog "logs/web2_access.log" common
cd D:\Apache2.2\bin
# 註冊服務名為 "Apache2.2_Web2",指定設定檔 web2.conf
httpd.exe -k install -n "Apache2.2_Web2" -f "D:\Apache2.2\conf\web2.conf"
# 驗證設定檔語法
httpd.exe -n "Apache2.2_Web2" -t
# 啟動服務
net start "Apache2.2_Web2"
# 或
httpd.exe -k start -n "Apache2.2_Web2"
| 操作 | 指令 |
|---|---|
| 安裝服務 (預設名 Apache2) | httpd.exe -k install |
| 安裝指定名稱服務 | httpd.exe -k install -n "服務名" |
| 安裝指定名稱+指定設定檔 | httpd.exe -k install -n "服務名" -f "路徑\conf\my.conf" |
| 移除服務 | httpd.exe -k uninstall / -n "服務名" |
| 啟動服務 | httpd.exe -k start [-n "服務名"] / net start "服務名" |
| 停止服務 | httpd.exe -k stop [-n "服務名"] / net stop "服務名" |
| 重啟服務 (重讀設定) | httpd.exe -k restart [-n "服務名"] |
| 測試設定檔語法 | httpd.exe -n "服務名" -t |
若不想用多埠,可在單一 httpd.conf 內設定 Name-based 虛擬主機:
Listen 80
NameVirtualHost *:80
ServerName www.site1.com
DocumentRoot "D:/www/web1"
...
ServerName www.site2.com
DocumentRoot "D:/www/web2"
...
需在 DNS/hosts 將網域解析到同一 IP。Windows 服務僅需一個 (預設 Apache2)。
apache.exe。httpd.exe,指令參數一致。Order allow,deny / Allow from all → Require all granted。https://localhost → 顯示 web1 內容。https://localhost:8080 → 顯示 web2 內容。logs/web2_error.log 無嚴重錯誤。