【Git】设置代理

Posted by 西维蜀黍 on 2023-04-03, Last Modified on 2023-05-02

Via .gitconfig

Globally

So, for example if your proxy server configuration is as follows:

Server: myproxyserver
Port: 8080
Username: mydomain\myusername
Password: mypassword

Then, add to your .gitconfig file using the following command:

git config --global http.proxy http://mydomain\\myusername:mypassword@myproxyserver:8080

# Method 1. git http + proxy http
git config --global http.proxy "http://127.0.0.1:1080"
git config --global https.proxy "http://127.0.0.1:1080"

# Method 2. git http + proxy shocks
git config --global http.proxy "socks5://127.0.0.1:1080"
git config --global https.proxy "socks5://127.0.0.1:1080"

# to unset
git config --global --unset http.proxy
git config --global --unset https.proxy

You can then verify that the command added the entry to your .gitconfig file successfully by doing cat .gitconfig:

At the end of the file you will see an entry as follows:

[http]
    proxy = http://mydomain\\myusername:mypassword@myproxyserver:8080

By Repository

If you just want to use proxy on a specified repository, don’t need on other repositories. The preferable way is the -c, --config <key=value> option when you git clone a repository. e.g.

$ git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git --config "http.proxy=proxyHost:proxyPort"

Via ~/.ssh/config

# via socks
Host git.evilcorp.com
	ProxyJump my_user@192.168.18.120
	
# git ssh + proxy http
vim ~/.ssh/config
Host github.com
HostName github.com
User git
ProxyCommand socat - PROXY:127.0.0.1:%h:%p,proxyport=1087

# git ssh + proxy socks
vim ~/.ssh/config
Host github.com
HostName github.com
User git
ProxyCommand nc -v -x 127.0.0.1:1080 %h %p

Host git.evilcorp.com
  # Identity file specifies wich SSH key used to access the git server.
  Identityfile ~/.ssh/id_rsa
  # ProxyCommand does the magic to access the proxy server.
  ProxyCommand /bin/nc -X 5 -x 127.0.0.1:11080 %h %p

Cool detail: The DNS resolution is done by the proxy, so your machine doesn’t need to know about the corp DNS servers.

Reference