Ubuntu 中浏览器能使用代理,不代表 apt、Git 和终端程序会自动继承。可以按使用范围选择临时环境变量、用户级 shell 配置、apt 专用配置或 Git 配置。本文只说明客户端设置,不提供代理服务器地址。
安全提醒:不要把代理账号密码写入公开脚本、Git 仓库或 shell 历史。公司、学校和服务器环境应遵守网络策略;配置完成后要知道如何取消,避免 apt 或 Git 在代理关闭后一直报错。
临时设置终端 HTTP、HTTPS 和 SOCKS5 代理
export http_proxy="http://127.0.0.1:7890"
export https_proxy="http://127.0.0.1:7890"
export all_proxy="socks5h://127.0.0.1:7890"
export HTTP_PROXY="$http_proxy"
export HTTPS_PROXY="$https_proxy"
export ALL_PROXY="$all_proxy"
很多本地代理提供的是 HTTP CONNECT 端口,因此 https_proxy 的地址仍写 http://127.0.0.1:端口。只有明确提供 SOCKS5 端口时才设置 socks5h://,其中 h 表示域名也交给代理解析。
这种设置只对当前 shell 和它启动的子进程生效,关闭终端后消失,适合先测试:
curl -I https://github.com
git ls-remote https://github.com/git/git.git HEAD
给当前用户长期设置代理
确认临时设置有效后,再把需要的变量写入 ~/.bashrc 或当前 shell 对应配置文件。建议手动编辑,避免多次执行 echo >> 产生重复行:
nano ~/.bashrc
source ~/.bashrc
不要默认写入 /etc/profile 给所有用户和服务使用。systemd 服务通常不会读取交互式 shell 配置,需要在服务自己的 override 中单独设置。
为 apt 单独配置代理
apt 更适合使用专用配置文件。创建或编辑:
sudo nano /etc/apt/apt.conf.d/80proxy
HTTP 代理端口示例:
Acquire::http::Proxy "http://127.0.0.1:7890/";
Acquire::https::Proxy "http://127.0.0.1:7890/";
apt 本身并不通用支持把 Acquire::https::Proxy 直接写成 SOCKS URL。只有 SOCKS 端口时,应使用代理工具提供的 HTTP 端口,或使用经过审查的转发方案。
为 Git 设置全局或单次代理
git config --global http.proxy "http://127.0.0.1:7890"
git config --global https.proxy "http://127.0.0.1:7890"
git config --global --get-regexp 'http.*proxy'
只想让单次 clone 使用代理,可以这样写:
git -c http.proxy="http://127.0.0.1:7890"
clone https://github.com/OWNER/REPOSITORY.git
只让单次 apt 命令使用代理
sudo apt-get
-o Acquire::http::Proxy="http://127.0.0.1:7890/"
-o Acquire::https::Proxy="http://127.0.0.1:7890/"
update
注意 sudo 可能清理当前用户的环境变量,所以把 apt 代理作为 -o 参数传入通常更明确。
如何取消 Ubuntu、apt 和 Git 代理
unset http_proxy https_proxy all_proxy
unset HTTP_PROXY HTTPS_PROXY ALL_PROXY
sudo rm -f /etc/apt/apt.conf.d/80proxy
git config --global --unset-all http.proxy
git config --global --unset-all https.proxy
如果写入过 ~/.bashrc,还要删除对应 export 行并重新打开终端。取消后用 env | grep -i proxy 和 git config --global --get-regexp proxy 检查残留。