How to rewrite git URLs to clone faster and push safer

• 2 minutes read

Whenever you wants to clone a git repository, you will take one of the following two options:

  1. visit the repository page in a browser, copy the repository url, go back to the terminal, type git clone and paste the repository url.
  2. type the whole repository url by hand.

I usually use the first one when browsing/exploring open source projects I find out there. But for personal/work projects is waste of time both of these options. I would say that for almost all personal/work repositories, the project name is the only part that changes in the repository URL. Thus, we can take advantage of a little-known git functionality: URL rewrite.

With URL rewrite, you can use a different format for repository URLs. For example, instead of use this:

git clone git@github.com:jweslley/dotfiles

You can use:

git clone gh:dotfiles

To enable this URL rewrite you need to edit your global git config file (~/.gitconfig) and add these lines:

[url "git@github.com:jweslley/"]
  insteadOf = gh:

You also can add multiple URL rewrites. For example, I use one for GitHub and another for GitLab. For more information, check out my ~/.gitconfig.

Always push using SSH authentication

Additionally, you are also able to rewrite URLs for push. This is useful when you want to guarantee you are using SSH authentication for pushes. For this, you can create a configuration section in ~/.gitconfig like:

[url "git@github.com:"]
  pushInsteadOf = https://github.com/
  pushInsteadOf = git://github.com/

This ensures that pushes will always use SSH authentication, even if the remote URL specifies https:// or git://. For example, a URL like https://github.com/jweslley/dotfiles.git will be rewritten to git@github.com:jweslley/dotfiles for pushes, but pulls will still use the original URL.

For more details, visit the official documentation: