跳到主要内容

Linux上搭建代理服务器

目的

之前介绍的shadowsocks用起来比较复杂,ssh加密隧道也不是长久之计,因此寻找了一种简单、长期有效的代理方式。

快速搭建简单易用的http代理服务器,同时要做好各类黑白名单管控。

举例要求:

使用squid搭建代理服务器

  • 代理端口设置为31000
  • 仅允许192.168.1.1/24和10.10.2.3使用代理
  • 同时为代理设置白名单,仅允许访问8.8.8.8、112.31.21.12、baidu.com、qq.com

安装

sudo apt update
sudo apt install -y squid
# 备份配置文件
sudo cp /etc/squid/squid.conf /etc/squid/squid.conf.bak

编辑配置文件/etc/squid/squid.conf,内容如下:

  • 简单版:
# 设置监听端口
http_port 31000
# 设置DNS
dns_nameservers 8.8.8.8

# 白名单 - 允许访问代理的客户端 IP 范围
acl allowed_clients src 192.168.1.0/24
acl allowed_clients src 10.10.2.3

# 白名单 - 允许访问的目标 IP
acl whitelist_ip dst 8.8.8.8
acl whitelist_ip dst 112.31.21.12

# 白名单 - 允许访问的目标域名(支持子域)
acl whitelist_domain dstdomain .baidu.com
acl whitelist_domain dstdomain .qq.com

# 放行符合条件的访问(必须同时满足:来源 IP 和目标 IP/域名)
http_access allow allowed_clients whitelist_ip
http_access allow allowed_clients whitelist_domain

# 默认拒绝所有
http_access deny all
  • 饱满点
# 基础配置
http_port 31000
dns_nameservers 8.8.8.8
cache_log /var/log/squid/cache.log
cache_store_log none
cache_effective_user proxy
# 日志格式
access_log /var/log/squid/access.log combined
logformat combined %>a %[ui %[un [%tl] "%rm %ru HTTP/%rv" %>Hs %h" "%{User-Agent}>h" %Ss:%Sh

# 禁用缓存(按需配置)
cache deny all

# 安全头设置
via off
forwarded_for delete
request_header_access Via deny all
request_header_access X-Forwarded-For deny all

# 定义客户端白名单
acl allowed_clients src 192.168.1.0/24 10.10.2.3/32

# 定义目标地址白名单
acl whitelist_ips dst 8.8.8.8 112.31.21.12
acl whitelist_domains dstdomain .baidu.com .qq.com

# 端口安全控制
acl Safe_ports port 80 # http
acl Safe_ports port 443 # https
acl SSL_ports port 443
acl CONNECT method CONNECT

# 访问控制规则
http_access deny !Safe_ports # 阻止非常规端口
http_access deny CONNECT !SSL_ports # 只允许SSL端口CONNECT

# 允许白名单客户端访问目标资源
http_access allow allowed_clients whitelist_ips
http_access allow allowed_clients whitelist_domains

# 默认拒绝所有其他请求
http_access deny all

修改后重启:

# 检查配置,无报错即配置正确
sudo squid -k check

# 重启
sudo systemctl restart squid

# 如果只是修改了配置文件,可以使用以下命令重新加载配置,而不中断当前连接
sudo squid -k reconfigure

验证

# 允许使用代理的客户端IP
curl -x http://your_proxy_ip:31000 http://www.baidu.com # 通
curl -x http://your_proxy_ip:31000 http://www.gm7.org # 不通

# 其他任意IP调用代理
curl -x http://your_proxy_ip:31000 http://www.baidu.com # 不通

实时日志:

tail -f /var/log/squid/access.log

后续使用

Linux

# 终端挂代理
export https_proxy=http://your_proxy_ip:31000 http_proxy=http://your_proxy_ip:31000 all_proxy=http://your_proxy_ip:31000

# 单独使用
sudo https_proxy=http://your_proxy_ip:31000 http_proxy=http://your_proxy_ip:31000 all_proxy=http://your_proxy_ip:31000 apt update

Windows

# cmd挂代理
set http_proxy=http://your_proxy_ip:31000
set https_proxy=http://your_proxy_ip:31000

电脑全局设置:

打开“设置” -> 搜索“代理” -> 打开“使用代理服务器” -> 填写“代理IP和端口”,保存即可

部分工具存在代理配置功能,按要求配置即可。