如何在 Composer 中使用 config.github-protocols 来选择 git 或 https 协议?

24次阅读

composer 默认优先用 git 协议(ssh)克隆 github 仓库,但在防火墙或 CI 环境中易失败;可通过 config.github-protocols 设为 ["https"] 强制走 HTTPS,支持项目级、全局级和临时命令行三种设置方式,适用于无 SSH 权限等场景。

如何在 Composer 中使用 config.github-protocols 来选择 git 或 https 协议?

Composer 默认会优先使用 git 协议克隆 GitHub 仓库(例如 git@github.com:vendor/package.git),但这在某些受限网络环境(如公司防火墙、CI/CD 环境)下可能失败。你可以通过 config.github-protocols 明确指定 Composer 应该用 git 还是 https(或两者)来访问 GitHub。

作用和默认行为

该配置控制 Composer 解析 github.com 域名时使用的协议前缀。默认值是 ["git", "https"],意味着 Composer 会先尝试 git://(实际走 SSH 或 HTTPS 的 git 协议封装),失败再回退到 https://。但如果你明确设为 ["https"],它就只走 HTTPS,绕过 SSH 密钥和 git 端口(9418)限制。

设置方式

有三种常用设置位置,按优先级从高到低:

  • 项目级(推荐):在项目根目录的 composer.json 中添加:

"config": {   "github-protocols": ["https"] }

然后运行 composer updatecomposer install 生效。

  • 全局级:对当前用户所有项目生效:

composer config -g github-protocols '["https"]'

  • 临时命令行:仅本次命令生效(适合调试):

composer install --github-protocols=https

常见组合与适用场景

你可以传入一个字符串数组,顺序决定尝试优先级:

如何在 Composer 中使用 config.github-protocols 来选择 git 或 https 协议?

星绘

豆包旗下 ai 写真、P 图、换装和视频生成

如何在 Composer 中使用 config.github-protocols 来选择 git 或 https 协议? 429

查看详情 如何在 Composer 中使用 config.github-protocols 来选择 git 或 https 协议?

  • ["https"]:强制走 HTTPS,适合无 SSH 权限、代理环境、CI 构建(如 GitHub Actions 默认支持)
  • ["git", "https"]:默认行为,兼顾速度(git 协议通常更快)和兼容性
  • ["https", "git"]:先试 HTTPS,失败再试 git —— 很少需要,除非你明确想降级体验

注意:git 协议在这里不指 git://(已废弃),而是指类似 git@github.com:user/repo.git 这种 SSH 形式;Composer 会根据是否配置了 SSH key 自动选择走 SSH 或回退到 HTTPS。

验证是否生效

执行 composer install -vcomposer update -v,观察日志中克隆 URL:

  • 看到类似 Cloning https://github.com/symfony/console.git → 表示 https 生效
  • 看到类似 Cloning git@github.com:symfony/console.git → 表示仍走 SSH/git 协议

也可用 composer config github-protocols 查看当前生效值(项目级优先于全局)。

基本上就这些。不复杂但容易忽略 —— 尤其在 CI 报 “Permission denied (publickey)” 或 “Failed to clone” 时,加一行 "github-protocols": ["https"] 往往就能解决。

text=ZqhQzanResources