在有条件的情况下, 设置代理能为我们节省很多时间, 让我们开始
-
连接情况总览
1.1 如果远程仓库的格式像下面这样, 这种就是使用
HTTP
或HTTPS
协议连接到Git
仓库的情况http://github.com/xxx-xxx/xxxx.git https://github.com/xxx-xxx/xxxx.git
1.2 如果远程仓库的格式像下面那样, 这种就是使用
SSH
协议连接到Git
仓库的情况git@github.com:xxx-xxx/xxxx.git ssh://git@github.com/xxx-xxx/xxxx.git
-
使用
HTTP
或HTTPS
协议连接到Git
仓库的代理方法2.1 针对 所有 域名的
Git
仓库# http/https 协议, port 需与代理软件设置一致 git config --global http.proxy http://127.0.0.1:port # socks5 协议 git config --global http.proxy socks5://127.0.0.1:port
—-global
选项指的是修改Git
的全局配置文件~/.gitconfig
,而非各个Git
仓库里的配置文件.git/config
.port
则为端口.
2.2 针对特定域名的Git
仓库
# http/https 协议 git config --global http.url.proxy http:127.0.0.1:port # 以 GitHub 为例 git config --global http https://github.com proxy http://127.0.0.1:port # SOCKS5 协议 git config --global http.url.proxy socks5://127.0.0.1:port # 以 GitHub 为例 git config --global http.https://github.comproxy socks5://127.0.0.1:port
注意:
url
即为需要走代理的仓库域名,url
以http://
和https://
打头的均用这个方法。- 网上很多中文教程,可能会告诉你
https://
打头的url
使用git config --global https.https://ecample.proxy protocol://127.0.0.1:port
,这种做法其实是错误的!记住一点:Git
不认https.proxy
,设置http.proxy
就可以支持https
了。 - 如果想了解
url
的更多模式, 如子域名等的情况, 可参照Git
的官方文档, 网页内容搜索http..*
, 即可找到相关信息.
-
使用
SSH
协议连接到Git
仓库的代理方法Git
依靠ssh
处理连接, 为了通过代理进行连接, 必须配置ssh
本身, 在~/.ssh/config
文件中设置ProxyCommand
选项.Linux
和macOS
是通过nc
来执行ProxyCommand
的,Windows
下则是通过connect
.3.1
Linux
和macO
用户3.1.1 编辑
~/.ssh/config
文件, 给文件加上如下对应内容# http 代理 Host github.com User git ProxyCommand nc -X connect -x 127.0.0.1:port %h %p
(但是我的
macOS
的相关配置是在/Users/mac/.gitconfig
里面)# 配置指定域名 socks5 代理 [http "https://github"] com = socks5://127.0.0.1:1090 # 配置全局 http 代理 [http] proxy = http://127.0.0.1:41091
解释:
Host
后面接的github.com
是指定要走代理的仓库域名;- 在
ProxyCommand
中,Linux
和macOS
用户用的是nc
; -X
选项后面接的是connect
, 意思是HTTPS
代理;-X
选项后面加上代理地址和端口号;- 在调用
ProxyCommand
时,%h
和%p
将会被自动替换为目标主机名和SSH
命令指定的端口(%h
和%p
不要修改, 保留原样即可).
3.1.2
# SOCKS5 协议 # 两种方式任选一个 # 第一种 Host github.com User git ProxyCommand nc -X 5 -x 127.0.0.1:port %h %p # 第二种 Host github.com User git ProxyCommand nc -x 127.0.0.1:port %h %p
解释:
Host
后面接的github.com
是指定要走代理的仓库域名;- 在
ProxyCommand
中,Linux
和macOS
用户用的是nc
; - 在调用
ProxyCommand
时,%h
和%p
将会被自动替换为目标主机名和SSH
命令指定的端口(%h
和%p
不要修改, 保留原样即可). - 如果
-X
选项后面接的是数字5, 那么指的就是socks5
代理 - 当然不写上
-X
选项也是可以的, 因为在没有指定协议的情况下,默认是使用socks5
代理的, 所以两种写法效果都一样, 都指的是走socks5
代理
3.2Windows
用户
编辑
~/.ssh/config
文件,给文件加上如下对应内容,windows
的~
路径一般是C:\Users\用户名
, 可在git bash
中输入cd ~
进入~
目录, 再用pwd
命令显示当前路径.# HTTP 代理 Host github.com User git ProxyCommand connect -H 127.0.0.1:port %h %p # SOCKS5 代理 Host github.com User git ProxyCommand connect -S 127.0.0.1:port %h %p
解释:
Host
后面接的github.com
是指定要走代理的仓库域名;- 在
ProxyCommand
中,windows
用户用的是connect
; -H
选项的意思是HTTP
代理;-S
选项指的就是socks5
代理;- 在调用
ProxyCommand
时,%h
和%p
将会被自动替换为目标主机名和SSH
命令指定的端口(%h
和%p
不要修改, 保留原样即可).
-
取消
git config --globl --unset http.proxy git config --global --unset https.proxy
评论区