萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Windows 下 Apache 2.2 安裝與虛擬目錄配置完整指南

前言

Apache HTTP Server 是全球最流行的 Web 伺服器之一。本文以 Apache 2.2.x 為例,記錄在 Windows 平台上的安裝流程、關鍵配置項與虛擬目錄/虛擬主機設定要點,供快速部署參考。正式環境請務必閱讀官方文檔。

一、下載與版本選擇

  • 官網:https://httpd.apache.org/
  • 無需 SSL:下載 Apache 2.x.x-win32-x86-no_ssl.msi
  • 需 SSL:下載 Apache 2.x.x-win32-x86-openssl-x.x.x.msi
  • 版本兼容性提醒:2.0 與 2.2 的模組(.so/.dll)不互相兼容,請根據應用程式需求選擇對應版本。

二、安裝步驟

  1. 雙擊 MSI 執行安裝精靈。
  2. Server Information:輸入正確的網域名或 IP(無 DNS 時填 IP)。
  3. 安裝類型:建議選 "for All Users, on Port 80, as a Service",Apache 將註冊為系統服務並開機自啟。
  4. 端口衝突處理:若 80 埠被 IIS 或其他程式佔用,安裝會失敗。解決辦法:
    • 編輯 Apache安裝目錄/conf/httpd.conf
    • 將 Listen 80 改為未用埠(如 Listen 81)
    • 重新執行安裝程式
  5. 安裝完成後,瀏覽器訪問 https://localhost,出現預設頁面即成功。

三、服務帳戶安全建議

預設 Apache 以 Local System 帳戶運行,權限過高。建議:

  1. 建立專用服務帳戶(如 apache_svc),僅授予必要權限。
  2. 「服務」管理單元 → Apache2.2 → 登入 → 選「此帳戶」輸入專用帳戶密碼。
  3. 重啟服務生效。

四、核心配置文件 httpd.conf 詳解

配置文件位於 安裝目錄/conf/httpd.conf,修改後請用「開始功能表 → Apache HTTP Server 2.2 → Test Configuration」驗證語法。

1. 文檔根目錄

DocumentRoot "D:/Programs/Apache2.2/htdocs"

使用正斜線 /,避免 Windows 反斜線轉義問題。

2. 虛擬目錄(Alias)

# 帶尾斜線:訪問 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>

3. URL 重導向

# 永久重導向 (301)
Redirect permanent /foo/ https://www.example.com/bar/

4. 虛擬主機(Name-based)

# 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 FoundDocumentRoot/Alias 路徑是否存在、重導向規則衝突
PHP 不解析載入 php7_module、AddHandler application/x-httpd-php .php、DirectoryIndex index.php

六、快速驗證清單

  • [ ] httpd -t 語法通過
  • [ ] 服務狀態「正在執行」
  • [ ] https://localhost 顯示預設頁
  • [ ] https://localhost/webpath/ 可訪問虛擬目錄
  • [ ] 虛擬主機 https://site1.local 正確解析
  • [ ] SSL 測試(如啟用):https://localhost 憑證有效

結語

Windows 上部署 Apache 2.2 核心在於:正確選擇安裝包、解決埠衝突、配置 httpd.conf 與 httpd-vhosts.conf、並給予虛擬目錄恰當的 <Directory> 權限。養成「改配置 → Test Configuration → 重啟服務 → 查 error.log」的閉環習慣,能解決 90% 以上的部署問題。

copyright © 萬盛學電腦網 all rights reserved