在做网站过程中有很多情况下需要让服务器的出网请求全部走另外一台服务器,例如一些国外服务器封禁邮件端口,想让邮件服务代理中转;或者服务器无防御,想让出网请求全部代理,防止被人找出真实IP。
这里是使用iptables实现OUTPUT链转发到v2ray实现透明代理。
首先需要在代理服务器安装好V2ray,作为服务端,然后在需要改出网请求的服务器也安装V2ray,作为客户端。(此处安装过程略)
客户端v2ray配置文件如下:
{ "inbounds": [ { "port": 12345, //开放的端口号 "listen": "127.0.0.1", "protocol": "dokodemo-door", "settings": { "network": "tcp,udp", "followRedirect": true // 这里要为 true 才能接受来自 iptables 的流量 }, "sniffing": { "enabled": true, "destOverride": ["http", "tls"] } } ], "outbounds": [ { "tag": "proxy", "protocol": "vmess", //你的代理服务器配置 "settings": { "vnext": ... }, "streamSettings": { "sockopt": { "mark": 255 //这里是 SO_MARK,用于 iptables 识别,每个 outbound 都要配置;255可以改成其他数值,但要与下面的 iptables 规则对应 }, } }, { "tag": "direct", "protocol": "freedom", "settings": {}, "streamSettings": { "sockopt": { "mark": 255 } } }, { "tag": "block", "protocol": "blackhole", "settings": { "response": { "type": "http" } } } ] }
配置完成后重启v2ray
然后执行以下命令配置iptables:
echo net.ipv4.ip_forward=1>>/etc/sysctl.conf
sysctl -p
iptables -t nat -N V2RAY
iptables -t nat -A V2RAY -d 127.0.0.0/8 -j RETURN
iptables -t nat -A V2RAY -d 你的服务器IP/32 -j RETURN
iptables -t nat -A V2RAY -p tcp -j RETURN -m mark --mark 0xff
iptables -t nat -A V2RAY -p tcp -j REDIRECT --to-ports 12345
iptables -t nat -A OUTPUT -p tcp -j V2RAY
注意要替换里面的服务器IP,如果服务器IP是内网的,那就只填内网的就行,可以通过ifconfig命令查看
执行以下命令查看当前出网IP,可判断是否生效:
curl ip.sb