Using Git insteadOf to Automatically Replace HTTPS URLs with SSH
When working with Git repositories, you often encounter URLs in HTTPS format, especially when cloning from GitHub, GitLab, or other hosting services. However, if you prefer using SSH for authentication (which is often more convenient with key-based auth), manually changing URLs can be tedious. Also, it can be even harder when dealing with submodules.
Git's insteadOf
configuration option provides an elegant solution by automatically rewriting URLs on the fly.
git config --global url."git@github.com:".insteadOf "https://github.com/"
git config --global url."git@gitlab.com:".insteadOf "https://gitlab.com/"
git config --global url."git@bitbucket.org:".insteadOf "https://bitbucket.org/"
You can also be more specific and target only certain repositories or services. For example, if you want to replace HTTPS URLs for some repositories, you can do:
git config --global url."git@github.com:meziantou/".insteadOf "https://github.com/meziantou/"
Once configured, Git automatically rewrites URLs:
# The following command
git clone https://github.com/user/repo.git
# Becomes equivalent to
git clone git@github.com:user/repo.git
The rewriting happens transparently. You can still use HTTPS URLs in commands, documentation, or when copying from web interfaces.
Another use-case of insteadOf
is to add authentication to a URL. For example, if you want to use a specific user for all git requests, you can do:
git config --global url."https://<token>@github.com/".insteadOf "https://github.com/"
Do you have a question or a suggestion about this post? Contact me!