Composer install 卡在 HTTPS 克隆是因为企业网络限制出向 HTTPS,需强制改用 SSH:配置 github-protocols: ["ssh"] 并确保 SSH key 已添加且被 Git 正确识别。

为什么 composer install 会卡在 Git 克隆 HTTPS 地址上?
很多内网或企业环境禁用了出向 HTTPS(比如只放行 80/443 的白名单策略),但 Composer 默认用 HTTPS 协议拉取 Git 包(尤其是 Packagist 上声明了 source 为 https://github.com/xxx/yyy.git 的包)。这时候你会看到类似这样的错误:
Failed to clone https://github.com/symfony/console.git via https, ssh protocols
注意:它其实尝试了 SSH,但失败了——说明问题不在协议切换本身,而在 SSH 配置没生效或没被 Composer 识别。
怎么让 Composer 强制走 SSH 而不是 HTTPS?
核心是重写 Git URL 映射,告诉 Composer:“所有 GitHub 域名的 HTTPS 地址,都替换成对应的 SSH 地址”。这靠 Composer 的 gitlab-domains 和 github-domains 配置不管用,得用更底层的 url 重写机制。
- 运行:
composer config -g repo.packagist composer https://packagist.org(确保全局源正常) - 添加 URL 重写规则:
composer config -g github-protocols ssh - 更可靠的方式(推荐):直接编辑全局配置文件
~/.composer/config.json,加入:
{
"repositories": {
"packagist": false,
"packagist.org": {
"type": "composer",
"url": "https://packagist.org"
}
},
"config": {
"github-protocols": ["ssh"],
"gitlab-protocols": ["ssh"]
}
}
⚠️ 注意:github-protocols 是 Composer 2.2+ 才支持的配置项;老版本需改用 git@github.com: 替换逻辑,但不如这个直接。
SSH key 没配好,Composer 就算想走 SSH 也连不上
即使配置了 github-protocols,如果本地 SSH key 没加到 ssh-agent 或没上传到 GitHub,依然会报 Permission denied (publickey)。验证和修复步骤:
- 检查是否已有可用 key:
ssh -T git@github.com—— 成功应返回 Hi xxx! You've successfully authenticated... - 如果没有输出或报错,先生成 key:
ssh-keygen -t ed25519 -C "your_email@example.com" - 把 key 加进 agent:
eval "$(ssh-agent -s)" && ssh-add ~/.ssh/id_ed25519 - 把公钥内容(
cat ~/.ssh/id_ed25519.pub)粘贴到 GitHub → Settings → SSH and GPG keys
特别注意:Composer 调用的是系统级 Git,不是你终端里当前用户的交互式 shell 环境。如果你用的是 systemd user session、Docker 或 CI 环境,ssh-agent 很可能没启动或没继承环境变量 —— 这时候 ssh-add 的 key 对 Composer 不可见。
某些私有包仍走 HTTPS?检查 composer.json 里的 repositories
如果你的项目 composer.json 里手动加了私有仓库,比如:
"repositories": [
{
"type": "vcs",
"url": "https://gitlab.example.com/mygroup/myrepo.git"
}
]
那这个 URL 不受 github-protocols 控制。必须显式改成 SSH 格式:
"url": "git@gitlab.example.com:mygroup/myrepo.git"
同时确保该域名的 SSH key 已配置(ssh -T git@gitlab.example.com 能通),且 Git 能解析该 host(必要时在 ~/.ssh/config 中加 Host gitlab.example.com 块)。
最易忽略的一点:Composer 的 config 设置是分作用域的 —— 项目级配置(composer config 不带 -g)会覆盖全局,而某些 CI 脚本会自动写入 HTTPS 源。务必用 composer config --list 查清最终生效的是哪一层。










