Composer私有包SSH认证的关键是确保Git能通过SSH拉取代码:需生成并添加SSH密钥到agent,composer.json中repositories的url必须为git@host:path.git格式,且Git服务器已配置对应公钥。

在 Composer 中为私有包配置 SSH 密钥认证,核心是让 Git 能通过 SSH 正确拉取代码,Composer 本身不直接处理密钥,而是依赖系统级的 Git 和 SSH 配置。只要 Git 能用 git clone git@xxx 成功克隆仓库,Composer 就能正常安装私有包。
确保 SSH 密钥已生成并添加到 SSH agent
先确认你本地已有可用的 SSH 密钥(如 ~/.ssh/id_rsa 或 ~/.ssh/id_ed25519)。如果没有,运行:
ssh-keygen -t ed25519 -C "your_email@example.com"eval "$(ssh-agent -s)"ssh-add ~/.ssh/id_ed25519
然后测试是否能免密访问目标 Git 服务器(如 GitHub/GitLab):
ssh -T git@github.com(应返回欢迎信息)
在 composer.json 中正确声明私有仓库
在项目根目录的 composer.json 中,添加 repositories 字段,类型设为 vcs,URL 使用 SSH 格式:
"repositories": [
{
"type": "vcs",
"url": "git@github.com:your-org/your-private-package.git"
}
]
⚠️ 注意:不能用 HTTPS 地址,也不能写成 https://... 或带用户名密码的格式;必须是 git@host:path.git 形式,否则 SSH 认证不会生效。
可选:配置 SSH config 简化多主机管理
如果你对接多个私有 Git 服务(如 GitHub、GitLab、自建 Gitea),可在 ~/.ssh/config 中做别名映射,例如:
Host github-enterprise HostName your.ghe.example.com User git IdentityFile ~/.ssh/id_rsa_ghe Host gitlab-custom HostName gitlab.example.com User git IdentityFile ~/.ssh/id_rsa_gitlab
之后在 composer.json 中就可以写:
"url": "git@gitlab-custom:group/pkg.git"
这样既安全又便于维护。
验证与常见问题
运行 composer install 或 composer update,观察是否成功拉取私有包。若失败,常见原因有:
- SSH agent 未启动或密钥未添加(
ssh-add -l查看) - Git 服务器未添加公钥(把
cat ~/.ssh/id_*.pub内容粘贴到对应平台的 SSH Keys 设置里) - Composer 缓存了旧的 HTTPS URL(执行
composer clear-cache) - PHP 进程运行用户与当前终端用户不同(如 Web 服务器用 www-data 用户时,需为其单独配置 SSH 密钥和 agent)
基本上就这些。关键不是改 Composer,而是让底层 Git + SSH 走通。










