Composer在代理环境下需配置HTTP/HTTPS代理,否则无法连接packagist.org;推荐使用composer config -g http-proxy单独设置,兼顾安全与生效范围,注意大小写、协议前缀及密码URL编码。

Composer 在代理环境下需要手动配置 HTTP 和 HTTPS 代理,否则会因无法连接 packagist.org 等源而报错(如 Connection timed out 或 Unable to connect)。
设置全局代理环境变量
Composer 会读取系统级的 http_proxy 和 https_proxy 环境变量。这是最常用且对所有命令生效的方式:
- Linux/macOS:在终端中运行(临时):
export http_proxy="http://proxy.example.com:8080"
export https_proxy="http://proxy.example.com:8080" - Windows(CMD):
set http_proxy=http://proxy.example.com:8080
set https_proxy=http://proxy.example.com:8080 - Windows(PowerShell):
$env:http_proxy="http://proxy.example.com:8080"
$env:https_proxy="http://proxy.example.com:8080"
若需长期生效,可将 export/set 命令写入 shell 配置文件(如 ~/.bashrc、~/.zshrc)或 Windows 系统环境变量设置中。
为 Composer 单独配置代理(推荐)
使用 composer config 命令设置仅影响 Composer 的代理,更安全、不干扰其他工具:
- 设置 HTTP/HTTPS 代理(当前项目):
composer config http-proxy http://proxy.example.com:8080
composer config https-proxy http://proxy.example.com:8080 - 设置全局代理(所有项目):
composer config -g http-proxy http://proxy.example.com:8080
composer config -g https-proxy http://proxy.example.com:8080
代理地址支持带认证格式:http://user:pass@proxy.example.com:8080。注意:密码含特殊字符时需 URL 编码(如 @ → %40)。
验证与调试代理是否生效
执行以下命令确认配置已加载并测试连通性:
- 查看当前配置:
composer config -g http-proxy(或省略-g查本地) - 尝试更新包源信息:
composer clear-cache && composer diagnose—— 正常应显示HTTP proxy support is enabled,且无网络错误 - 若仍失败,用
composer -v update查看详细请求日志,确认是否走代理、是否被拦截或认证失败
特殊情况处理
某些企业代理会拦截 HTTPS 请求或要求忽略证书校验(不推荐,仅临时调试):
- 跳过 SSL 验证(⚠️仅测试用,有安全风险):
composer config -g secure-http false - 若代理只允许 HTTP 协议访问 Packagist,可改用 HTTP 源(不推荐):
composer config -g repo.packagist.org.url http://packagist.org - 遇到 DNS 解析失败,可尝试在代理配置后加
?no-tls或检查代理是否支持 SNI
基本上就这些。代理配置本身不复杂,但容易忽略大小写(如 https_proxy 不是 HTTPS_PROXY)、协议前缀(必须是 http://,不能漏)或认证编码问题。










