DEV Community

Jonhnny Weslley
Jonhnny Weslley

Posted on • Originally published at jonhnnyweslley.net on

How to rewrite git URLs to clone faster and push safer

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

Enter fullscreen mode Exit fullscreen mode

You can use:

git clone gh:dotfiles

Enter fullscreen mode Exit fullscreen mode

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:

Enter fullscreen mode Exit fullscreen mode

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/

Enter fullscreen mode Exit fullscreen mode

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:

Originally posted here.

Top comments (0)