Git Configuration Based on Remote Repositories
Git Configuration Based on Remote Repositories
Problem
Git applies settings from your ~/.gitconfig to every repository. This is useful for defaults but becomes a problem when repositories or remotes need different identities or settings, for example:
- Different user identities or signing keys for different remotes (github, gitlab, bitbucket).
- Frequently switching between private and public remotes, which forces manual overrides.
- Managing multiple SSH keys and per-host commit signing.
These situations often require editing or overriding your global config.
Using includeIf Conditional Configuration
Git's includeIf directive allows you to conditionally include configuration files based on certain criteria, such as the presence of a specific remote URL.
hasconfig:remote.*.url checks if any remote URL matches the specified pattern. This enables you to load different configuration files based on the remote repository's host.
How it works
- Use
~/.ssh/configto select the right SSH key per host. - Use Git's
includeIfto load host-specific.gitconfigonly when a repository uses that remote. - Configure commit signing per host and register allowed signers on the server.
This is for Windows, but the same principles apply to Linux and macOS. Just adjust file paths accordingly.
I am using different SSH keys for authentication and signing commits for GitHub and GitLab. You can use the same key for both, but I prefer separate keys.
Step-by-step setup
1. Create a SSH config file at ~/.ssh/config
# github
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_github_auth
IdentitiesOnly yes
# gitlab
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_ed25519_gitlab_auth
IdentitiesOnly yes
~/.ssh/configis optional but useful if you use different SSH keys for different hosts. It ensures the correct key is used for authentication.
2. Create a Git configuration file for GitLab at ~/.gitconfig-gitlab
[user]
signingkey = C:\\Users\\username\\.ssh\\id_ed25519_gitlab_sign.pub3. Update your global Git configuration at ~/.gitconfig to include the GitLab config when a repository uses a GitLab remote.
[user]
name = thisisrick25
email = swapnaneel06@gmail.com
signingkey = C:\\Users\\username\\.ssh\\id_ed25519_github_sign.pub
[filter "lfs"]
clean = git-lfs clean -- %f
smudge = git-lfs smudge -- %f
process = git-lfs filter-process
required = true
[gpg]
format = ssh
[commit]
gpgsign = true
[includeIf "hasconfig:remote.*.url:*gitlab.com*/**"]
path = ~/.gitconfig-gitlab
[includeIf "hasconfig:remote.*.url:https://gitlab.com/**"]
gitlab.com*/**is used for SSH remotes for GitLab.https://gitlab.com/**is used for HTTPS remotes for GitLab.