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

Squid 透明代理網關部署實戰:NAT 上網、快取加速與多層存取控制策略

編輯:Linux 教學

前言

Squid 是功能最完整的開源 HTTP/HTTPS 代理快取伺服器。結合 iptables NAT 與 REDIRECT 機制,可部署為透明代理網關:客戶端無需任何瀏覽器設定,所有 HTTP 流量自動經過 Squid 快取與存取控制。本文以 CentOS 為例,完整示範從安裝、NAT 設定、透明代理配置、多層 ACL 策略(檔案類型/大小/域名/關鍵字)到驗證封鎖效果的全流程。

架構拓樸

  • Client LAN:192.168.100.0/24
  • Squid Gateway:雙網卡
    - eth0 (LAN):192.168.100.254
    - eth1 (WAN):公網 IP 或上游路由器 DHCP
  • Internet Test Server:提供 HTTP 下載測試

網路拓樸圖

一、安裝 Squid 並啟用服務

yum install -y squid
systemctl enable --now squid

安裝畫面

二、開啟核心轉發與 SNAT(NAT 上網)

# 1. 開啟 IP 轉發
echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p

# 2. SNAT 規則(假設 eth1 為 WAN 介面)
iptables -t nat -A POSTROUTING -o eth1 -s 192.168.100.0/24 -j MASQUERADE
service iptables save

SNAT 設定

三、配置 Squid 透明代理與基礎快取

編輯 /etc/squid/squid.conf 關鍵段落:

# 監聽 LAN 介面 3128 埠,啟用透明模式
http_port 192.168.100.254:3128 transparent

# 基礎權限
acl all src all
http_access allow all

# 快取參數
maximum_object_size 3 MB          # 超過 3MB 不快取
reply_body_max_size 8 MB all      # 禁止下載超過 8MB 檔案

# 日誌
access_log /var/log/squid/access.log squid

四、iptables REDIRECT 規則(核心步驟)

# 將 LAN 來自 80 埠的 TCP 流量重導至本機 3128
iptables -t nat -A PREROUTING -i eth0 -s 192.168.100.0/24 -p tcp --dport 80 -j REDIRECT --to-ports 3128
service iptables save

REDIRECT 規則

規則生效確認

五、客戶端驗證(無需設定代理)

客戶端直接瀏覽 https://test.server/largefile.zip,觀察 Squid access.log 確認 TCP_HIT/TCP_MISS 狀態。
客戶端瀏覽測試

六、進階 ACL 存取控制策略

在 squid.conf 中新增:

# 定義 LAN 網段
acl lan100 src 192.168.100.0/24

# 1. 封鎖特定域名
acl denydomain dstdomain .qq.com .tencent.com .xxxx.com

# 2. 關鍵字過濾(URL 路徑含 sex/adult)
acl denywords urlpath_regex -i sex adult

# 3. 副檔名過濾(禁止下載 rmvb/mp3)
acl realfile urlpath_regex -i \.rmvb$ \.mp3$

# 應用拒絕規則(順序很重要:先匹配越精確的規則)
http_access deny lan100 denydomain
http_access deny lan100 denywords
http_access deny lan100 realfile

# 保留原有允許規則
http_access allow lan100
http_access deny all

七、重載 Squid 並驗證封鎖效果

systemctl reload squid

1. 封鎖 .rmvb/.mp3 下載

rmvb 封鎖

mp3 封鎖

2. 檔案大小限制(>3MB 不快取、>8MB 直接拒絕)

大小限制1

大小限制2

3. 域名封鎖

域名封鎖

4. 關鍵字過濾

含 "sex"、"adult" 的 URL 直接回傳 403/錯誤頁。

八、維運提醒

  • HTTPS 透明代理:需部署 SSL-Bump(中間人解密),涉及憑證信任與法律合規,謹慎評估。
  • 快取目錄大小:cache_dir ufs /var/spool/squid 10240 16 256 依磁碟容量調整。
  • 日誌分析:定期用 sarg、lightsquid 產生報表。
  • 效能調校:maximum_object_size_in_memory、memory_cache_size 依實體記憶體設定。
Copyright © Windows教程網 All Rights Reserved