Press Ctrl/Cmd + P to print
or save as PDF

Redirecting In Linux VPS Server With Nginx

Nginx is an open-source HTTP web server and also one of the most well-known web servers for its performance. By using Nginx in your VPS, you have the ability to redirect the URL of a website to another address. In this article, we will guide you on how to redirect your page with Nginx and how you may use them in your Linux VPS server

Redirect Page

Firstly, you will have to access the VPS using SSH. Most of the page redirects can be achieved using the inbuilt rewrite feature with Nginx. It is a feature of Nginx by default and can be used in both temporary and permanent redirects. You may paste the following code in the directory “etc/nginx/site-enabled/default” to redirect a page to another link.

Location path_pattern {
      rewrite ^/oldURL$ https://www.domainame.com/newURL redirect;
}

Replace the “domainname” url above with a domain of your own that you wanted to redirect to. To allow it to redirect it permanently. replace “redirect” with “permanent”.

Redirect Domain

server {
      listen 80;
      hostname casbay.in www.casbay.in;
      rewrite ^ http://www.casbay.com$request_uri? permanent;
}

In the example above, we are redirecting www.casbay.in to the domain www.casbay.com permanently.

Redirect HTTP to HTTPS (SSL)

HTTPS protects you from the Man In The Middle attack (MITM) and it is better to use it over HTTP. You need a SSL certificate in order to make this redirect by adding this code into the same file.

server {
listen 80 default_server
server_name _;
return 301 https://$host$request_uri;
}

Redirect to Another Site

This is helpful when you are hosting multiple sites or applications at once and needed to link them. Use the following code into the similar file as above for this redirect.

server{
listen 80;
server_name casbay.in;
     return 301 https://casbay.in$request_uri;
}

Redirect to non-www From www

Most users would rather just type in a URL such as “casbay.com” instead of “www.casbay.com” as the longer the URL, the more the user would have to type. To allow users to enter the website directly without the “www”, use the following code.

server {
    server_name www.casbay.com;
    return 301 $scheme://casbay.com$request_uri;
}

For all the redirects changes made with Nginx to take effect, you would need to restart Nginx web server using the following command.

sudo systemctl restart Nginx