當您的網站訪問速度不盡如人意時,部署 Squid 作為 HTTP 加速器(反向代理)是一種經典且高效的優化方案。本文將詳細介紹如何在 Linux 環境下配置 Squid 透明代理至後端 Apache,實現靜態資源緩存與動態請求分發,顯著降低後端負載並提升用戶體驗。
假設您已安裝 Red Hat 系列發行版,可直接使用 RPM 包安裝 Squid:
yum install squid -y
# 或
rpm -ivh squid-*.rpm
編輯 /etc/squid/squid.conf,以下為關鍵指令詳解:
http_port 80
icp_port 0
acl QUERY urlpath_regex cgi-bin \?
no_cache deny QUERY
cache_mem 16 MB
cache_dir ufs /tmp 256 16 256
cgi-bin 或 ?)禁用緩存,確保數據實時性。/tmp,容量 256MB,一級子目錄 16 個,二級子目錄各 256 個(ufs 為傳統存儲格式)。log_icp_queries off
buffered_logs on
emulate_httpd_log on
redirect_rewrites_host_header off
half_closed_clients off
acl all src 0.0.0.0/0.0.0.0
http_access allow all
cache_mgr admin
cache_effective_user squid
cache_effective_group squid
httpd_accel_host 210.51.0.124
httpd_accel_port 81
這兩條指令告訴 Squid:「收到請求後,轉發給 210.51.0.124:81」。
只需修改 httpd.conf 使 Apache 監聽 81 端口:
Listen 81
# 若使用 NameVirtualHost,請同步修改:
NameVirtualHost *:81
重啟 Apache:systemctl restart httpd(或 service httpd restart)。
systemctl restart squid
# 查看存取日誌確認加速生效
tail -f /var/log/squid/access.log
日誌中出現 TCP_HIT 或 TCP_MEM_HIT 即表示緩存命中,加速生效。
若需單一 Squid 加速多個域名,請改用以下配置:
httpd_accel_host virtual
httpd_accel_uses_host_header on
同時 Apache 需配置:
Listen 8080
NameVirtualHost *:8080
<VirtualHost *:8080>
ServerName site1.com
...
</VirtualHost>
<VirtualHost *:8080>
ServerName site2.com
...
</VirtualHost>
關鍵在於 httpd_accel_uses_host_header on 讓 Squid 根據客戶端發送的 Host 頭決定轉發目標,配合 Apache 同端口虛擬主機即可實現多站點加速。
通過「Squid 監聽 80 → 緩存靜態資源 → 轉發動態請求至 Apache:81」的架構,可大幅降低後端壓力、縮短響應時間。配合虛擬主機設置,單節點即可承載多站點加速需求。生產環境建議進一步調整 cache_dir 大小、啟用 refresh_pattern 精細控制緩存過期策略,並監控 cache.log 確保穩定運行。