Skip to content

Instantly share code, notes, and snippets.

@dongfg
Created June 24, 2025 05:52
Show Gist options
  • Save dongfg/6386032c415adae8a5d98bcd3b4a40a3 to your computer and use it in GitHub Desktop.
Save dongfg/6386032c415adae8a5d98bcd3b4a40a3 to your computer and use it in GitHub Desktop.
自动在 WSL 中根据宿主机网关动态设置 http_proxy 和 https_proxy
# WSL Host Proxy zsh Plugin
# Description: 自动在 WSL 中根据宿主机网关动态设置 http_proxy 和 https_proxy
# Usage:
# 1. 将此文件放到 ~/.oh-my-zsh/custom/plugins/wsl-host-proxy/wsl-host-proxy.plugin.zsh
# 2. 在 ~/.zshrc 的 plugins=(...) 中添加 "wsl-host-proxy"
# 3. 重新加载 zsh:`source ~/.zshrc`
# ===== 配置 =====
# 可在 ~/.zshrc 中自定义 PROXY_PORT(默认 7890)
: ${PROXY_PORT:=7890}
# 更新代理环境变量函数
_update_wsl_host_proxy() {
# 获取 WSL 默认网关(即宿主机)IP
local gw
gw=$(ip route show default 2>/dev/null | awk '/default/ {print $3; exit}')
[[ -z "$gw" ]] && return
# 构造代理地址
local proxy_url="http://$gw:$PROXY_PORT"
# 同时导出大小写环境变量
export http_proxy="$proxy_url"
export https_proxy="$proxy_url"
export HTTP_PROXY="$proxy_url"
export HTTPS_PROXY="$proxy_url"
}
# 首次执行
_update_wsl_host_proxy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment