
Composer 为什么突然报 403 API rate limit exceeded
GitHub 对未认证的 API 请求有严格限速(每小时 60 次),Composer 安装/更新依赖时频繁调用 GitHub API(比如获取 composer.json、解析 dist URL、检查 tag),一旦触发限速,就会卡在 Fetching package information 或直接报错:Could not fetch https://api.github.com/...: 403 API rate limit exceeded。这不是 Composer 本身的问题,而是你没告诉它“你是谁”。
怎么让 Composer 用你的 GitHub 令牌
核心是把 GitHub Personal Access Token 写进 Composer 的全局配置,让它每次请求都带上 Authorization: Bearer <token></token>。操作分三步:
- 去
https://github.com/settings/tokens/new创建新 token,勾选repo(必须)和read:packages(如果用 GitHub Packages)即可,不用给 admin 权限 - 在终端运行:
composer config -g github-oauth.github.com <your_token_here></your_token_here>(注意域名是github.com,不是api.github.com) - 验证是否生效:
composer config -g --list | grep github-oauth,应看到对应条目
之后所有项目(包括 create-project)都会自动携带认证头。Token 存在 ~/.composer/auth.json,权限建议设为 600(chmod 600 ~/.composer/auth.json),避免被其他用户读取。
为什么 auth.json 里写 github.com 而不是 api.github.com
因为 Composer 内部做了域名映射:只要请求目标是 GitHub 的任何子域(api.github.com、github.com、raw.githubusercontent.com),它都会查 auth.json 中 github.com 对应的 token 并复用。如果你误写成 api.github.com,Composer 就不会匹配到——它只认你配置的 host 名字,不解析子域继承关系。
常见错误现象:composer install 仍报 403,但 composer config -g --list 看到的是 github-oauth.api.github.com。删掉重配成 github.com 就行。
私有仓库或 GitHub Enterprise 怎么配
如果是公司内网的 GitHub Enterprise(比如 https://git.example.com),不能复用 github.com 的配置,得单独指定 host:
- 生成 token 时,目标是你的 GHE 实例(
https://git.example.com/settings/tokens),权限同样只需repo - 运行:
composer config -g github-oauth.git.example.com <token></token>(host 必须和实际 API 域名完全一致,含端口也要写上) - 确保
composer.json里的仓库源(repositories)也指向该域名,否则 Composer 不会触发认证
注意:GHE 默认关闭 API 访问限制,但若启用了 SAML SSO,token 还需额外授权(页面弹窗确认),否则仍会 403。
Token 本身没过期时间,但一旦泄露或离职就得立刻删掉;另外,如果换机器或 CI 环境,别忘了同步 auth.json 或用环境变量方式注入(COMPOSER_AUTH),不然又回到匿名限速状态。










