可通过环境变量或composer config命令配置代理,支持http/https及认证代理,设置后可正常下载包并用命令检查配置。

在使用 Composer 时,如果网络环境受限(比如公司内网或特定地区),可以通过配置代理来正常访问网络资源。以下是配置 Composer 使用代理的几种方式。
1. 设置 HTTP 和 HTTPS 代理
Composer 支持通过环境变量设置代理,适用于大多数操作系统。
将以下环境变量添加到你的系统中:
- HTTP_proxy 或 http_proxy:用于 HTTP 请求
- HTTPS_PROXY 或 https_proxy:用于 HTTPS 请求
- NO_PROXY 或 no_proxy:指定不走代理的域名
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
export NO_PROXY=localhost,127.0.0.1
在 windows 命令行中:
set HTTP_PROXY=http://proxy.example.com:8080
set HTTPS_PROXY=http://proxy.example.com:8080
配置后,Composer 会自动使用这些代理设置。
2. 在 Composer 配置中设置代理
也可以直接通过 composer config 命令设置代理,仅对当前项目或全局生效。
全局设置代理:
composer config –global http-proxy http://proxy.example.com:8080
composer config –global https-proxy http://proxy.example.com:8080
取消代理设置:
composer config –global –unset http-proxy
composer config –global –unset https-proxy
3. 处理认证代理
如果代理需要用户名和密码,可以在代理地址中包含认证信息:
http://username:password@proxy.example.com:8080
例如:
composer config –global http-proxy http://john:secret123@proxy.company.com:8080
注意:密码中若含特殊字符(如 @、:),需进行 URL 编码。
4. 检查当前配置
查看当前 Composer 的代理配置:
composer config –global http-proxy
composer config –global https-proxy
也可查看全部配置:
composer config –list –global
基本上就这些。只要代理设置正确,Composer 就能顺利下载包。如果仍连接失败,检查代理地址、端口、防火墙或尝试用 -vvv 参数查看详细错误信息。


