搭建 Squid HTTP 代理服务器
Generated by claude-sonnet-4-6
Squid 是一个成熟的 HTTP 代理服务器,支持 HTTP/HTTPS 代理、访问控制和 Basic Auth 认证。
安装
以 Ubuntu 为例,安装 Squid 和 htpasswd 工具:
sudo apt install squid apache2-utils
配置认证
-
创建密码文件并添加用户:
sudo htpasswd -c /etc/squid/passwd <username>将
<username>改成实际用户名。第一次创建密码文件使用-c,后续添加用户不要加-c,否则会覆盖原文件。 -
创建认证配置:
sudoedit /etc/squid/conf.d/auth.confauth_param basic program /usr/lib/squid/basic_ncsa_auth /etc/squid/passwd acl authenticated proxy_auth REQUIRED acl SSL_ports port 80 http_access allow authenticated -
检查配置并重启服务:
sudo squid -k parse sudo systemctl restart squid sudo systemctl enable squid
防火墙
系统防火墙
如果启用了 ufw,需要放行 Squid 默认端口 3128:
sudo ufw allow 3128/tcp
sudo ufw reload
sudo ufw status
也可以只允许自己的 IP 访问:
sudo ufw allow from 1.2.3.4 to any port 3128 proto tcp
将
1.2.3.4改成自己的公网 IP。即使配置了用户名密码认证,也建议尽量限制来源 IP。
云服务商防火墙
DigitalOcean、AWS 等云平台在系统层之上还有独立的网络防火墙,即使系统 ufw 未启用,也可能因云防火墙未放行而导致端口不通。
以 DigitalOcean 为例,使用 doctl 添加入站规则:
# 查看防火墙列表
doctl compute firewall list
# 在已有防火墙上放行 3128 端口
doctl compute firewall add-rules <firewall-id> \
--inbound-rules "protocol:tcp,ports:3128,address:0.0.0.0/0 protocol:tcp,ports:3128,address:::/0"
验证
检查 Squid 是否监听端口:
ss -ltnp | grep 3128
使用 curl 测试代理:
$ curl -I --proxy http://username:'password'@server.example.com:3128 https://example.com
HTTP/1.1 200 Connection established
HTTP/2 200
也可以先在服务器本机测试:
curl -I --proxy http://username:'password'@127.0.0.1:3128 https://example.com
客户端配置
代理地址格式:
http://username:password@server.example.com:3128
终端中临时使用:
export http_proxy="http://username:password@server.example.com:3128"
export https_proxy="http://username:password@server.example.com:3128"
https_proxy这里仍然使用http://开头,因为客户端是用 HTTP CONNECT 方法通过 Squid 转发 HTTPS 流量。
维护
查看日志:
sudo tail -f /var/log/squid/access.log # 代理请求记录(客户端 IP、目标 URL、响应状态、用户名等)
sudo tail -f /var/log/squid/cache.log # Squid 运行日志(启动、配置加载、错误信息等)
修改用户密码:
sudo htpasswd /etc/squid/passwd <username>
sudo systemctl reload squid
添加用户:
sudo htpasswd /etc/squid/passwd user2
sudo systemctl reload squid
参见:

浙公网安备 33010602011771号