首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Apache 伺服器完整配置指南:從基礎設置到虛擬主機與 SSL 加密

     編輯:PHP 綜合知識

Apache HTTP Server 是全球最廣泛使用的開源 Web 伺服器軟體,其核心配置檔案為 httpd.conf。本文將系統性地梳理 Apache 的關鍵配置項,涵蓋基礎參數、多處理模組(MPM)優化、HTTP 標頭控制、持久連線、別名與 CGI 設定、使用者目錄、日誌管理、使用者認證、虛擬主機架構、SSL/TLS 加密部署、Gzip 壓縮、存取控制、頻寬限制與反向代理等實戰主題,協助管理員構建高效、安全、可維護的生產環境。

一、核心基礎配置

啟動 Apache 時,首先讀取 ServerRoot 指定的安裝根目錄,所有相對路徑均以此為基準。PidFile 記錄主進程 ID,Listen 定義監聽埠(預設 80),ServerName 設定主機名稱,ServerAdmin 填寫管理員信箱,DocumentRoot 指向網站根目錄。

ServerRoot "/mnt/software/apache2"
PidFile logs/httpd.pid
Listen 80
ServerName www.example.com:80
ServerAdmin admin@example.com
DocumentRoot "/mnt/web/example"

目錄存取控制 <Directory>

對網站根目錄授予權限時,常用指令說明如下:

  • Options:FollowSymLinks 允許符號連結;Indexes 無索引檔時列出目錄;ExecCGI 執行 CGI;SymLinksIfOwnerMatch 僅擁有者相同時允許連結。
  • AllowOverride:None 忽略 .htaccess(效能最佳);All 允許所有覆寫指令;亦可細分為 AuthConfig、FileInfo 等。
  • Order / Allow / Deny:舊版 2.2 語法,Order allow,deny 表示先評估 Allow 再評估 Deny;新版 2.4+ 建議改用 Require all granted。
<Directory "/mnt/web/example">
    Options FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

預設首頁檔案

DirectoryIndex index.html index.htm index.php

二、多處理模組(MPM)效能調校

Apache 2.x 編譯時透過 --with-mpm 選擇工作模式,執行 httpd -l 可查看編譯模組:

1. Prefork MPM(預設、相容舊模組)

每個請求佔用一個獨立子進程,記憶體佔用較大但穩定。

<IfModule prefork.c>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild 1000
</IfModule>
  • StartServers:啟動初始進程數。
  • Min/MaxSpareServers:空閒進程池水位。
  • MaxClients:最大並發連線數,受限於記憶體。
  • MaxRequestsPerChild:子進程處理請求上限,防止記憶體洩漏,建議 1000。

2. Worker MPM(執行緒模式,高並發)

進程內建立固定執行緒池,較省記憶體,適合高流量站點。

<IfModule worker.c>
    StartServers         2
    MaxClients         150
    MinSpareThreads     25
    MaxSpareThreads     75
    ThreadsPerChild     25
    MaxRequestsPerChild 1000
</IfModule>

3. Perchild MPM(多站點隔離)

固定子進程數,動態調整執行緒,適合虛擬主機服務商。

三、HTTP 回應標頭與安全性

ServerTokens Prod
ServerSignature Off
  • ServerTokens Prod:僅回傳 "Apache",隱藏版本號與模組資訊。
  • ServerSignature Off:錯誤頁面不顯示伺服器版本資訊。

四、持久連線

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 30

啟用後同一 TCP 連線可傳輸多個請求,降低握手開銷;KeepAliveTimeout 建議 5-30 秒平衡資源佔用。

五、別名、CGI 與使用者目錄

Alias 虛擬目錄映射

Alias /download/ "/var/www/download/"
<Directory "/var/www/download">
    Options Indexes MultiViews
    AllowOverride AuthConfig
    Require all granted
</Directory>

ScriptAlias CGI 目錄

ScriptAlias /cgi-bin/ "/mnt/software/apache2/cgi-bin/"
<Directory "/mnt/software/apache2/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

CGI 腳本需具備執行權限(chmod +x)。

UserDir 個人網站

UserDir public_html
# URL https://example.com/~user/ 對應 /home/user/public_html/

需確保家目錄權限 chmod 755 /home/user。

六、日誌管理

錯誤日誌

ErrorLog logs/error_log
LogLevel warn

存取日誌與自訂格式

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog logs/access_log combined

常用格式變數:%h 客戶 IP、%t 時間、%r 請求行、%>s 狀態碼、%b 回傳位元組、%{Referer}i 來源頁、%{User-Agent}i 瀏覽器標識。

七、基本認證(Basic Auth)

  1. httpd.conf 允許目錄使用 .htaccess:AllowOverride AuthConfig
  2. 建立密碼檔:htpasswd -c /var/httpuser/passwords username
  3. 目錄下 .htaccess 內容:
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /var/httpuser/passwords
Require user username

八、虛擬主機完整範例

基於 IP

<VirtualHost 192.168.1.10:80>
    DocumentRoot /www/site1
    ServerName www.site1.com
</VirtualHost>
<VirtualHost 192.168.1.11:80>
    DocumentRoot /www/site2
    ServerName www.site2.org
</VirtualHost>

基於域名(單 IP 多域名)

NameVirtualHost *:80
<VirtualHost *:80>
    DocumentRoot /www/site1
    ServerName www.site1.com
    ServerAlias site1.com *.site1.com
</VirtualHost>
<VirtualHost *:80>
    DocumentRoot /www/site2
    ServerName www.site2.org
</VirtualHost>

混合 IP + 域名 + 多埠

結合 Listen、NameVirtualHost、<VirtualHost ip:port> 彈性部署。

九、SSL/TLS 加密部署

核心配置 conf/ssl.conf

Listen 443
SSLPassPhraseDialog builtin
SSLSessionCache dbm:/usr/local/apache2/logs/ssl_scache
SSLSessionCacheTimeout 300
SSLMutex file:/usr/local/apache2/logs/ssl_mutex

<VirtualHost _default_:443>
    DocumentRoot "/usr/local/apache2/htdocs"
    ServerName www.example.com:443
    SSLEngine on
    SSLCipherSuite HIGH:!aNULL:!MD5
    SSLCertificateFile /usr/local/apache2/conf/ssl.crt/server.crt
    SSLCertificateKeyFile /usr/local/apache2/conf/ssl.key/server.key
    CustomLog /usr/local/apache2/logs/ssl_request_log \
        "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>

自簽憑證快速產生(測試用)

# 1. 私鑰
openssl genrsa -des3 -out server.key 2048
# 2. CSR
openssl req -new -key server.key -out server.csr
# 3. 自簽憑證(有效 1 年)
openssl req -x509 -days 365 -key server.key -in server.csr -out server.crt

生產環境請向受信 CA(如 Let's Encrypt、DigiCert)申請正式憑證。

十、Gzip 壓縮傳輸

LoadModule deflate_module modules/mod_deflate.so
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/javascript application/json

可額外排除舊版瀏覽器或二進位檔案避免損壞。

十一、存取控制與頻寬限制

IP 白名單

<Directory "/var/www/admin">
    Require ip 192.168.1.0/24 10.0.0.1
</Directory>

模組 mod_bw / mod_cband 限制頻寬與連線數

<Location /download>
    BandWidth all 51200
    MaxConnection all 30
    BandWidthError 510
</Location>

十二、反向代理

ProxyRequests Off
ProxyPass /app/ https://backend.example.com/app/
ProxyPassReverse /app/ https://backend.example.com/app/

配合 mod_proxy、mod_proxy_http 實現負載均衡與微服務網關。

十三、完整 VirtualHost 範本

<VirtualHost *:80>
    ServerName app.example.com
    ServerAlias www.app.example.com
    DocumentRoot "/var/www/app/public"
    DirectoryIndex index.php
    
    <Directory "/var/www/app/public">
        Options FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/app_error.log
    CustomLog ${APACHE_LOG_DIR}/app_access.log combined
</VirtualHost>

本指南涵蓋 Apache 從安裝調校到生產部署的核心知識點,建議根據實際流量與業務需求逐項驗證調整。持續關注官方安全公告,及時更新版本與憑證,才能維持穩定安全的 Web 服務。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved