When working with Git repositories, you often encounter HTTPS URLs, especially when cloning from GitHub, GitLab, or other hosting services. If you prefer SSH for authentication (which is more convenient with key-based authentication), manually converting URLs can be tedious. This becomes even harder when dealing with submodules.
Git's insteadOf configuration option solves this by automatically rewriting URLs.
Shell
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 organizations. For example, to rewrite URLs only for a specific user:
Shell
git config --global url."git@github.com:meziantou/".insteadOf "https://github.com/meziantou/"
Once configured, Git automatically rewrites URLs:
Shell
# 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 inject authentication into a URL. For example, to authenticate all Git requests using a token:
Shell
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!