Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 伺服器綜合

使用 Squid 反向代理大幅加速網站響應速度

編輯:伺服器綜合

前言

當您的網站訪問速度不盡如人意時,部署 Squid 作為 HTTP 加速器(反向代理)是一種經典且高效的優化方案。本文將詳細介紹如何在 Linux 環境下配置 Squid 透明代理至後端 Apache,實現靜態資源緩存與動態請求分發,顯著降低後端負載並提升用戶體驗。

環境準備

假設您已安裝 Red Hat 系列發行版,可直接使用 RPM 包安裝 Squid:

yum install squid -y
# 或
rpm -ivh squid-*.rpm

核心配置解析

編輯 /etc/squid/squid.conf,以下為關鍵指令詳解:

1. 監聽端口與 ICP 設定

http_port 80
icp_port 0
  • http_port 80:Squid 直接監聽 80 端口接收用戶請求,作為前端入口。
  • icp_port 0:關閉 ICP(Internet Cache Protocol)協議,單機部署無需緩存對等通信。

2. 緩存策略與存儲結構

acl QUERY urlpath_regex cgi-bin \?
no_cache deny QUERY
cache_mem 16 MB
cache_dir ufs /tmp 256 16 256
  • acl QUERY ... / no_cache deny QUERY:針對動態路徑(含 cgi-bin 或 ?)禁用緩存,確保數據實時性。
  • cache_mem 16 MB:分配 16MB 內存給熱門對象(in-transit objects 另計)。
  • cache_dir ufs /tmp 256 16 256:磁盤緩存目錄 /tmp,容量 256MB,一級子目錄 16 個,二級子目錄各 256 個(ufs 為傳統存儲格式)。

3. 日誌與性能優化

log_icp_queries off
buffered_logs on
emulate_httpd_log on
redirect_rewrites_host_header off
half_closed_clients off
  • 關閉 ICP 日誌、啟用緩衝寫入、模擬 Apache Combined 日誌格式、禁止重寫 Host 頭、關閉半閉合連接處理,均為減少 I/O 開銷。

4. 訪問控制與身份標識

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
  • 允許所有來源訪問(生產環境請按需限制),設置管理員郵箱與進程運行用戶/組。

5. 後端服務器映射(關鍵)

httpd_accel_host 210.51.0.124
httpd_accel_port 81
  • httpd_accel_host:真實 Web 服務器 IP(此處為 210.51.0.124,即 www.5ilinux.com)。
  • httpd_accel_port:真實 Web 服務器監聽端口(此處為 81)。

這兩條指令告訴 Squid:「收到請求後,轉發給 210.51.0.124:81」。

Apache 協同配置

只需修改 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 確保穩定運行。

Copyright © Windows教程網 All Rights Reserved