Today I learned…

that you can use SSH host aliases in git remote URLs!

First of all, here is my problem and use case:
I want to be able to have multiple remotes in a local git repo with different logins and of course different SSH keys, because I use one pair of SSH keys per connection. For repositories with only one remote I used to set core.sshCommand. This applies to every remote you configure. You could use the GIT_SSH_COMMAND environment variable on the command line to overwrite the core.sshCommand setting, because it would be prioritized. This could be done by writing it on the command line manually, or by using a shell alias, or git alias. None of these options are really practical in everyday use.

And that’s exactly where SSH host aliases come in handy!

First: What are SSH host aliases?

In your ~/.ssh/config you can have so-called host blocks to configure certain SSH connections. They start with the Host keyword and a pattern. That pattern can be very flexible - you can even list multiple patterns. For details check out the man (5) ssh_config page.

So, imagine the following two host blocks in your ~/.ssh/config:

Host website-on-git-server
    User lena
    IdentityFile ~/.ssh/lena@git@example.com
    Hostname git.example.com

Host website-on-web-server
    User wwwuser
    IdentityFile ~/.ssh/wwwuser@my-website.com
    Hostname my-website.com

Here website-on-git-server and website-on-web-server are the aliases we use in our git remote URLs.

Usually - so without the host aliases - the remote configs would look like this:

[remote "web"]
        url = ssh://my-website.com:/home/wwwuser/my-website.com.git
        fetch = +refs/heads/*:refs/remotes/web/*
[branch "main"]
        remote = web
        merge = refs/heads/main
[remote "git"]
        url = git@git.example.com:lena/website-sources.git
        fetch = +refs/heads/*:refs/remotes/git/*

and with aliases simply like this:

[remote "web"]
        url = ssh://website-on-web-server:/home/wwwuser/my-website.com.git
        fetch = +refs/heads/*:refs/remotes/web/*
[branch "main"]
        remote = web
        merge = refs/heads/main
[remote "git"]
        url = website-on-git-server:lena/website-sources.git
        fetch = +refs/heads/*:refs/remotes/git/*

So, to explain it in words: you simply replace the host part in the original remote URL with your SSH alias. This way you can easily configure many different remotes using many different identities and key files in a single repository

PS:
BTW I didn’t learn this today the first time. A couple of years ago somebody on the fediverse told me about this and I forgot it. So I still learned it today, but again