January 14, 2020

Nginx Redirect Domain

Directing visitors from one domain to another is very easy, just edit the nginx configuration file that has been created then add some configuration syntax or if you don’t want to edit an existing configuration file, you can also create 1 more configuration file.

The following example, anyone who accesses the *.redirect.sibunglon.com domain will be directed to the sibunglon.com domain. *= wilcard, so anyone who accesses the domain x.redirect.sibunglon.com, xyz.redirect.sibunglon.com, blog.redirect.sibunglon.com, and others will be directed to the sibunglon.com domain.

Okey, because I do not want to disturb the configuration file that I have made, so I just created a file to redirect the domain. Please use your favorite text editor, here I use vim.

$ sudo vi /etc/nginx/conf.d/redirect.conf

Then add the following script. Save and exit the text editor. Please change the user’s primary destination domain and destination domain when directed.

server {
   server_name *.redirect.sibunglon.com;
   return 301 $scheme://sibunglon.com;
   access_log  /var/log/nginx/redirect_access.log;
   error_log   /var/log/nginx/redirect_error.log  warn;

Make sure there are no nginx configurations, no errors or conflicts.

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Restart service nginx.

$ sudo systemctl restart nginx

Please access the main destination domain and you are directed to another domain as you set it in the nginx configuration.