Signup/Sign In
PUBLISHED ON: FEBRUARY 27, 2023

Redirect requests to a different domain using Nginx

In this tutorial, we will learn to use nginx for redirecting a domain/subdomain to another domain. You might want to use this feature if the service/website running on a subdomain or domain has been moved to a different domain. It also helps prevent broken links and improve SEO.

How to redirect a domain to another domain in nginx server?

For demonstration we are going to redirect domain.com and any of subdomain (sub.domain.domain.com) should be redirected to another-domain.com.

Create the configuration file for the domain in sites-available (or sites-enabled) sub-directory of nginx configuration directory i.e. /etc/nginx/sites-available/domain.com.conf.

$ sudo vim /etc/nginx/sites-available/domain.com.conf

Two different methods to send a user to different domain:

URL string and subdomain will be permanently redirected to another domain. Use one of these methods and put these lines in the configuration file.

Method 1: Using rewrite.

server {
  listen 80;
  server_name domain.com www.domain.com;
  rewrite ^ http://another-domain.com$request_uri? permanent;
}

Method 2(recommended): for nginx version 0.9.1 or higher. Using return with status code 301(Moved permanently) or 302 (found).

server {
  listen 80;
  server_name domain.com www.domain.com;
  return 301 http://www.another-domain.com$request_uri;
}

Replace domain.com and another-domain.com with your subdomain in the code above. All of the queries made to your website's domain.com will be redirected to another-domain.com. After the subdomain name in the requested URL $request_uri(URL stub after subdomain name). We issue a 301 redirection code in our response.

Finally, You can save the file and exit the text editor.

Verify our configuration, then launch Nginx.

It is a recommended practice to test new configurations before loading them to the production server because a single syntax mistake will prevent the Nginx service from running, which will prevent users from accessing your website. You can use the following command to do so.

$ sudo nginx -t -c /etc/nginx/sites-available/domain.com.conf

Enable the site if no issues were discovered. In order to accomplish this, we must build a symbolic link between the site configuration file and the sites-enabled directory using the following command:

$ sudo ln -s /etc/nginx/sites-available/domain.com.conf /etc/nginx/sites-enabled/domain.com.conf

Finally, Start/Restart/Reload the server to load the changes:

$ sudo systemctl restart nginx

or

$ sudo service nginx restart



About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.