Apache HTTP Server 通過 mod_proxy 及相關模組提供強大的反向代理與端口映射能力。本文整理實戰配置範例,涵蓋本地端口轉發、遠程 HTTPS 反向代理、WebSocket 支援、Cookie 路徑重寫等進階場景,並說明必要模組與常見坑點。
在 httpd.conf 中確保以下模組已載入(去掉註釋):
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule rewrite_module modules/mod_rewrite.so
將訪問 /yingshe 的請求轉發至內網服務 192.168.10.12:8080:
<VirtualHost *:80>
ServerName proxy.example.com
DocumentRoot "E:/www/yingshe"
<Directory "E:/www/yingshe">
Options -Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
</Directory>
# 核心代理指令
ProxyPass /yingshe https://192.168.10.12:8080/
ProxyPassReverse /yingshe https://192.168.10.12:8080/
<Proxy https://192.168.10.12:8080/>
Require all granted
</Proxy>
</VirtualHost>
關鍵說明:ProxyPassReverse 修正後端返回的 Location、Content-Location、URI 標頭,確保重定向指向代理地址而非內網地址。
Apache 監聽 8002 端口,反向代理至後端 HTTPS 服務:
Listen 8002
<VirtualHost *:8002>
SSLProxyEngine On # 必須開啟,允許代理 HTTPS 後端
ProxyRequests Off # 關閉正向代理,僅作反向代理
ProxyPass / https://192.168.10.201/
ProxyPassReverse / https://192.168.10.201/
# 解決 Session 丟失:重寫 Cookie Path
ProxyPassReverseCookiePath / https://192.168.10.201/ /
<Proxy https://192.168.10.201/>
Require all granted
</Proxy>
</VirtualHost>
注意:後端使用自簽證書時,需在 Apache 配置 SSLProxyVerify none 和 SSLProxyCheckPeerCN off SSLProxyCheckPeerName off 跳過證書驗證(僅限測試環境)。
前端用戶以 HTTP 訪問 Apache,Apache 以 HTTPS 連接後端:
Listen 80
<VirtualHost *:80>
ServerName app.example.com
SSLProxyEngine On
ProxyRequests Off
ProxyPass / https://backend.internal/
ProxyPassReverse / https://backend.internal/
ProxyPassReverseCookiePath /backend.internal/ /
</VirtualHost>
前後端均為 HTTPS,Apache 終結前端 SSL 再建立後端 SSL 連接:
Listen 443
<VirtualHost *:443>
ServerName secure.example.com
SSLEngine On
SSLCertificateFile /path/to/cert.pem
SSLCertificateKeyFile /path/to/key.pem
SSLProxyEngine On
ProxyRequests Off
ProxyPass / https://backend.internal/
ProxyPassReverse / https://backend.internal/
ProxyPassReverseCookiePath /backend.internal/ /
</VirtualHost>
mod_proxy_wstunnel,使用 ProxyPass /ws/ ws://backend:8080/ws/。ProxyPass / https://backend/ connectiontimeout=300 timeout=600 keepalive=On 減少握手開銷。X-Forwarded-For 標頭,Apache 配置 RequestHeader set X-Forwarded-For "%{REMOTE_ADDR}s" (需 mod_headers)。mod_proxy_balancer 使用 BalancerMember 定義多後端,啟用 ProxyHCTemplate 定期健檢。ProxyErrorOverride On 配合 ErrorDocument 統一錯誤頁風格。apachectl configtest 或 httpd -tmod_status 並配置 <Location /server-status> SetHandler server-status </Location>LogLevel proxy:debug 觀察握手、轉發細節。合理運用 Apache 反向代理,可實現服務解耦、SSL 卸載、靜態動態分離、多應用共用 80/443 端口等架構目標。