commit to github through https proxy - downgoon/hello-world GitHub Wiki
内网环境通过https代理上传代码到github
问题描述
如何通过代理,走HTTPS协议,上传代码到 github 呢?
需求要点
- 代理设置: 用户网络环境不能直接访问github.com,需要通过代理访问。
- https协议:走https协议,不走 git 自有协议。
- 免密上传:不希望每次上传都输入账号密码。
实施概要
- 代理设置
git 设置代理有几种方式,先介绍系统环境变量的方式:
export http_proxy=http://proxyuser:proxypassword@proxyhost:proxyport
export https_proxy=https://proxyuser:proxypassword@proxyhost:proxyport
export no_proxy=localhost,127.0.0.0/8,*.local,10.0.0.0/8
- https协议
设置系统级代理后,直接 git clone
把代码拷下来:
git clone https://github.com/username/projectname.git
注意:此处使用的是 https 协议,而不是:
git clone [email protected]:username/projectname.git
- 免密上传
进入项目目录,编辑 .git/config
文件,在url前面增加github.com的账号和密码:
修改前url:
[remote "origin"]
url = https://github.com/username/projectname.git
fetch = +refs/heads/*:refs/remotes/origin/*
修改后url:
[remote "origin"]
url = https://githubuser:[email protected]/username/projectname.git
fetch = +refs/heads/*:refs/remotes/origin/*
修改点:
githubuser:[email protected]
, 当然如果你愿意每次输入密码,只需[email protected]
。
- 提交代码
git push origin master
此时提交代码,无需输入用户名和密码。
FAQ
- 账号密码是否会泄露?
问题:账号密码存放在项目的 .git/config ,会不会随项目一起上传,导致安全信息泄露?
答案:不会!!! 这就是 git 比 svn 厉害的地方之一(svn的账号密码会联同文件一同上传,而git对.git/config
只会选择性上传)。
- 提交时,携带账号参数?
问题:如果账号不配置在.git/config 里面,能否携带在命令行参数里面,比如:
git push origin master --username XXX --passowrd XXX
答案:不可以。
- 单独对项目设置代理?
问题:开发人员往往有多个项目,有些项目需要提交到内网,有些项目需要提交到github,因此不能用系统层代理。能不能针对每个项目分别设置代理?
答案:可以。git 配置文件分“全局”和“局部”:
- 全局配置:又名
global
,位置~/.gitconfig
和~/.gitignore
。 - 局部配置:又名
local
,位置$project_home/.git/config
和$project_home/.gitignore
。
# 设置项目级代理
git config --local http.proxy http://proxyuser:proxypassword@proxyhost:proxyport
git config --local https.proxy https://proxyuser:proxypassword@proxyhost:proxyport
# 取消代理
git config --local --unset http.proxy
git config --local --unset https.proxy
# 查看修改
$ cat .git/config
[http]
proxy = http://proxyuser:proxypassword@proxyhost:proxyport
[https]
proxy = http://proxyuser:proxypassword@proxyhost:proxyport
如果是全局的,把参数 --local
修改成 --global
即可。
- 能不能针对不同域设置不同代理
问题:每个项目单独设置代理,工作量重复了,能不能针对内网的gitlab域设置一个代理,针对github域设置一个代理,都在全局上设置?
答案:据说可以?但笔者简单实验时,未论证。
$ vi ~/.gitconfig
[http "http://github.com"]
proxy=http://proxyuser:proxypassword@proxyhost:proxyport
[https "https://github.com"]
proxy=http://proxyuser:proxypassword@proxyhost:proxyport
[http "http://inner.com"]
proxy=http://proxyuser:proxypassword@inner:port
[https "https://inner.com"]
proxy=http://proxyuser:proxypassword@inner:port