How to Change a Git Remote's URL

Updated on

2 min read

Git Change Remote

Git remote is a pointer that refers to another copy of the repository that is usually hosted on a remote server.

In some situations, like when the remote repository is migrated to another host, you need to change the remote’s URL.

This guide explains how to change the URL of a Git remote.

Changing a Git Remote’s URL

Each Git repository can have zero or more Git remotes linked to it. When you clone a repository, the name of the remote is set automatically to origin and points to the repository that you cloned from. If you created the repository locally, you can add a new remote .

The remote can point to a repository hosted on a Git hosting service such as GitHub, GitLab, and BitBucket or your private Git server .

Follow the steps below to change the URL of a remote:

  1. Change to the directory where the repository is located:

    cd /path/to/repository
  2. Run git remote to list the existing remotes and see their names and URLs:

    git remote -v

    The output will look something like this:

    origin	https://github.com/user/repo_name.git (fetch)
    origin	https://github.com/user/repo_name.git (push)
  3. Use the git remote set-url command followed by the remote name, and the remote’s URL:

    git remote set-url <remote-name> <remote-url>

    The remote’s URL can start with HTTPS or SSH, depending on the protocol you’re using. If no protocol is specified, it defaults to SSH. The URL can be found on the repository page of your Git hosting service.

    If you’re changing to HTTPS, the URL will look something like:

    https://gitserver.com/user/repo_name.git
    

    If you’re changing to SSH, the URL will look like:

    git@gitserver.com:user/repo_name.git
    

    For example, to change the URL of the origin to git@gitserver.com:user/repo_name.git you would type:

    git remote set-url origin git@gitserver.com:user/repo_name.git
  4. Verify that the remote’s URL was successfully changed by listing the remote connections:

    git remote -v

    The output should look like this:

    origin	ssh://git@gitserver.com:user/repo_name.git (fetch)
    origin	ssh://git@gitserver.com:user/repo_name.git (push)

That’s it. You have successfully changed the URL of the remote.

What the git remote set-url command does is update the repository .git/config file with a new URL to the remote repository.

.git/config
...

[remote "origin"]
        url = git@gitserver.com:user/repo_name.git
        fetch = +refs/heads/*:refs/remotes/origin/*

You can also change the remote’s URL by editing the .git/config file with a text editor . However, it is recommended to use the git command.

Conclusion

Changing a Git remote’s URL is as simple as running: git remote set-url <remote-name> <remote-url>.

If you hit a problem or have feedback, leave a comment below.