DevOps运维技术栈

squid正向代理配置

一、安装 Squid

# Ubuntu/Debian
sudo apt update && sudo apt install squid -y

# CentOS/RHEL
sudo yum install squid -y   # 或 dnf install squid -y

二、核心配置 /etc/squid/squid.conf

备份原配置:

sudo cp /etc/squid/squid.conf /etc/squid/squid.conf.bak
sudo vim /etc/squid/squid.conf

关键配置项(按需替换)

root@Ubuntu-0002:~# cat /etc/squid/squid.conf
# 1. 监听端口(客户端代理端口)
http_port 3128

# 2. 主机名(避免启动警告)
visible_hostname proxy-server

# 3. 缓存配置(可选,按需开启)
cache_dir ufs /var/spool/squid 1024 16 256
cache_mem 128 MB
maximum_object_size 8 MB

# 4. 日志路径
access_log /var/log/squid/access.log
cache_log  /var/log/squid/cache.log
cache_store_log none

# 5. 访问控制(ACL)
# 允许的内网网段(请替换为你的实际网段)
acl localnet src 192.168.12.0/24
#Squid默认对CONNECT是拒绝的,需添加
acl SSL_ports port 443
acl allowed_methods method GET POST HEAD 

#http_access allow CONNECT SSL_ports
# 放行合法网段,拒绝其他所有请求
http_access allow localnet
http_access allow allowed_methods
http_access deny all

# 6. 其他安全建议
http_access allow localhost
deny_info ERR_PROXY_DENIED all

connect_timeout 30 seconds
peer_connect_timeout 30 seconds

注意

  • http_access 规则按从上到下顺序匹配,必须将 allow 放在 deny all 之前。
  • cache_dir 大小单位是 MB,1024 表示 1GB 磁盘缓存。
  • 若不需要缓存,可注释 cache_dir 相关行,改为纯转发代理。

三、启动与验证

# 1. 初始化缓存目录(首次配置或修改 cache_dir 后必须执行)
sudo squid -z

# 2. 重启服务
sudo systemctl restart squid
sudo systemctl enable squid

# 3. 检查状态与监听端口
sudo systemctl status squid
ss -tlnp | grep 3128

四、客户端配置

生产环境建议

限制 HTTP 方法(防滥用):

acl safe_methods method GET POST HEAD
http_access allow safe_methods
http_access deny !safe_methods

基础认证(可选):

sudo apt install apache2-utils
sudo htpasswd -c /etc/squid/passwd admin   # 创建用户

配置中添加:

auth_param basic program /usr/lib64/squid/basic_ncsa_auth /etc/squid/passwd
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

退出移动版