~/.ssh/config: hosts and aliases

SSH · Practical · 10 min

A good config file replaces long command lines and is used by every SSH-based tool, from scp to Git to VS Code.

~/.ssh/config stores per-host settings. A Host line starts a block that applies to matching host names (patterns with * and ? work):

  • HostName is the real address; the Host name becomes an alias.
  • User, Port, IdentityFile set the login name, port and key.
  • IdentitiesOnly yes offers only the listed key, avoiding "Too many authentication failures" when the agent holds many keys.
  • ServerAliveInterval 60 sends keepalives so idle connections through NAT or firewalls do not drop.

The crucial rule: for each option, the first value found wins. ssh reads the file top to bottom and keeps the first match, so put specific Host blocks first and general defaults (Host *) at the end. Command-line -o options beat everything in the file.

Every tool that uses OpenSSH honours this file: scp web:file ., rsync, git clone git@github-work:org/repo.git and editors' remote features all use the alias.

To see what ssh will actually use for a host, run ssh -G web; it prints the fully resolved configuration. Include ~/.ssh/config.d/* lets you split a large config into files (put it near the top).

Example

# ~/.ssh/config
Host web
    HostName 203.0.113.10
    User deploy
    IdentityFile ~/.ssh/work_ed25519
    IdentitiesOnly yes

Host github-work
    HostName github.com
    User git
    IdentityFile ~/.ssh/work_ed25519

Host *
    ServerAliveInterval 60
    AddKeysToAgent yes

# usage:  ssh web     scp app.tgz web:/tmp/     git clone git@github-work:acme/api.git
# check:  ssh -G web | grep -E '^(user|hostname|port) '

Remember

  • Host blocks define aliases with HostName, User, Port, IdentityFile
  • First obtained value wins: specific blocks first, Host * last
  • ssh -G host prints the effective settings

Watch out for

  • Putting Host * with a User at the top; it then overrides every later block's User.

Check yourself

  1. Your config has `Host *` with `User root` at the top and `Host web` with `User deploy` below. Which user does `ssh web` use?
  2. Which command shows the configuration ssh will really use for a host?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: man.openbsd.org/ssh_config