gitlab https链接转为ssh链接
如果你最初使用 git clone https://… 方式拉取了 GitLab 仓库,后续想改用 SSH 协议进行操作(如免密推送/拉取),无需重新克隆仓库。以下是完整的切换步骤及原理说明:
🔧 一、切换远程仓库 URL(核心步骤)
查看当前远程地址
在仓库根目录执行:
git remote -v
输出示例:
origin https://gitlab.com/username/repo.git (fetch)
origin https://gitlab.com/username/repo.git (push)
修改为 SSH 协议地址
git remote set-url origin git@gitlab.com:username/repo.git
关键说明:
git@gitlab.com 是 SSH 协议的固定用户和域名格式[citation:4][citation:7];
username/repo.git 需替换为你的实际项目路径(与 HTTPS 路径一致)[citation:7];
再次运行 git remote -v 确认已切换为 git@gitlab.com:… 格式[citation:4][citation:8]。
🔐 二、SSH 密钥配置(若未配置)
若尚未配置 SSH 密钥,需先生成并添加到 GitLab:
生成密钥对
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" # 邮箱需与 GitLab 注册邮箱一致
按回车使用默认路径(~/.ssh/id_rsa),建议不设密码(直接回车)[citation:2][citation:4]。
添加公钥到 GitLab
复制公钥内容:
cat ~/.ssh/id_rsa.pub # 手动复制输出内容
登录 GitLab → Settings → SSH Keys → 粘贴公钥并保存[citation:2][citation:5]。
测试 SSH 连接
ssh -T git@gitlab.com
成功时会显示 Welcome to GitLab, @username![citation:2][citation:4]。