This guide explains how to set up Git to use different email addresses and GPG signing keys based on the remote repository URL.
You'll need to create three configuration files:
[tag]
gpgsign = true
[commit]
gpgsign = true
# Select correct user config depending on the remote (work GitLab or personal GitHub)
[includeIf "hasconfig:remote.*.url:git@YOUR_GITLAB_HOST:**"]
path = .gitconfig-work
[includeIf "hasconfig:remote.*.url:https://YOUR_GITLAB_HOST/**"]
path = .gitconfig-work
[includeIf "hasconfig:remote.*.url:git@github.com:**"]
path = .gitconfig-personal
[includeIf "hasconfig:remote.*.url:https://github.com/**"]
path = .gitconfig-personal[user]
email = your.work@email.com
name = Your Name
signingkey = YOUR_WORK_GPG_KEY_ID[user]
email = your.personal@email.com
name = Your Name
signingkey = YOUR_PERSONAL_GPG_KEY_ID- The main
.gitconfigcontains the global signing settings and URL-based conditions - When pushing to work GitLab (either via SSH or HTTPS), the work configuration is used
- When pushing to GitHub (either via SSH or HTTPS), the personal configuration is used
- All commits and tags are automatically signed with the appropriate GPG key
To verify which configuration is being used in a repository:
# Check the active email
git config --show-origin --get user.email
# Check the active GPG key
git config --show-origin --get user.signingkey
# Check the remote URL
git remote -vThe configuration supports both SSH and HTTPS URLs:
- SSH format:
git@hostname:username/repo.git - HTTPS format:
https://hostname/username/repo.git
- The
:**pattern is used for SSH URLs - The
/**pattern is used for HTTPS URLs - Configuration files should be stored in your home directory
- Make sure your GPG keys are properly set up in both GitLab and GitHub
- Replace all placeholder values (YOUR_GITLAB_HOST, your.work@email.com, etc.) with your actual information
What if you have two remotes on one repo and you want to use different user/email settings for each?
If
.gitconfiglooks like this:and the repo has both remotes, won't the user/email always be read from
.gitconfig-github?