FisherHub Blog
← 返回列表 | 工具笔记

WSL2 网络代理配置:让子系统访问宿主机代理

Clash、V2Ray、ShadowSocks——让 WSL2 中的 curl/npm/git 都能走 Windows 代理

问题

WSL2 本质是一个 Hyper-V 虚拟机,有独立的网络栈。Windows 上运行的代理软件(Clash/V2Ray)WSL2 默认访问不到。

获取宿主机 IP

# WSL2 中
cat /etc/resolv.conf | grep nameserver | awk '{print $2}'
# 通常是 172.xx.xx.1

配置代理脚本

# ~/.bashrc 或 ~/.zshrc
export HOST_IP=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}')

# Clash 默认端口
alias proxy='export https_proxy="http://$HOST_IP:7890" http_proxy="http://$HOST_IP:7890" all_proxy="socks5://$HOST_IP:7891"'
alias unproxy='unset https_proxy http_proxy all_proxy'

确保代理软件允许局域网连接

Clash 中设置 allow-lan: true,并确认防火墙允许入站连接。

Git 代理

# 临时
git config --global http.proxy http://$HOST_IP:7890
git config --global https.proxy http://$HOST_IP:7890

# 取消
git config --global --unset http.proxy
git config --global --unset https.proxy

npm 代理

npm config set proxy http://$HOST_IP:7890
npm config set https-proxy http://$HOST_IP:7890

一键启动脚本

#!/bin/bash
# proxy-on.sh
export HOST_IP=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}')
export http_proxy="http://$HOST_IP:7890"
export https_proxy="http://$HOST_IP:7890"
export all_proxy="socks5://$HOST_IP:7891"
echo "✅ Proxy ON: $HOST_IP:7890"

验证

proxy
curl -I https://google.com  # 应该能通

这个配置是所有 WSL2 用户的必修课,特别是做前端开发时需要频繁 npm install