How to Redirect Location to Another Domain in NGINX

Last updated on September 21st, 2021 at 11:04 am

You need to redirect old URLs to their new location, when you change website domain. Here’s how to redirect location to another domain in NGINX. You can also use these steps to redirect path to another domain, redirect folder to another domain, redirect 301 all request to another domain.

 

How to Redirect Location to Another Domain in NGINX

Here are the steps to redirect location to another domain in NGINX.

 

1. Open NGINX configuration file

If you are using NGINX’s main configuration file nginx.conf, without virtual hosts, then run the following command

$ sudo vi /etc/nginx/nginx.conf

If you have configured separate virtual hosts for your website (e.g www.mysite.com), such as /etc/nginx/sites-enabled/mysite.conf then open it with the following command

$ sudo vi /etc/nginx/sites-enabled/mysite.conf

Bonus Read : How to Change NGINX Port Number in Ubuntu

 

2. Redirect Location to Another Domain

Let’s say you want to redirect /product to new domain (www.newsite.com), then add the following location block inside your server block

server{
...
    location /product {
        rewrite ^/product(.*)$ https://www.newsite.com/$1 redirect;
    }
...
}

Let’s look at the above location block in detail

rewriterewrite command tells NGINX to change one or more URLs that match a given pattern (e.g /product) to another URL.

^/product – URL paths that start with /product. You can change it to another URL as you need it.

(.*) – match one or more characters. In our case, it means anything that follows /product

$ – end of string

$1 – URL part after /product

redirect – tells NGINX to redirect to another URL. It can also be a new domain, subdomain, subdirectory or even URL.

Bonus Read : How to Move NGINX Web Root to New Location

 

3. Restart NGINX

Run the following command to check syntax of your updated config file.

$ sudo nginx -t

 

If there are no errors, run the following command to restart NGINX server.

$ sudo service nginx reload #debian/ubuntu
$ systemctl restart nginx #redhat/centos

 

That’s it! Now NGINX will redirect all requests originally sent to www.mysite.com/product, to www.newsite.com. For example, www.mysite.com/product/shoes will be redirected to www.newsite.com/shoes

By the way, if you want to create charts & dashboards to monitor your business or website, you can try Ubiq. We offer a 14-day free trial.