Using Nginx to redirect requests

Share on:

Using Nginx to redirect requests to different URLs

There are some times requirement like sending traffic from http to https or redirecting requests from one domain to another. This can be easily done via Nginx. Below I am sharing a way to do it for different scenarios.

Assumptions/ Prerequisites

  1. You are using nginx to serve the requests.
  2. You have premissions to change config of nginx and restart it.

Scenario-1: Redirecting all the http traffic to https

  1. Add below piece of new server block to your nginx config file which contains server blocks
1# This is the block which will redirect the http traffic to https traffic
2server {
3        listen       80;
4        server_name  foo.com; # your server/domain name
5        return       301 https://foo.com$request_uri;
6}

There should be a server block which would be serving https request for this to work for example some thing like below

 1server {
 2        listen 443 ssl;
 3        listen [::]:443;
 4        server_name foo.com;
 5        ssl_certificate /some/path/to/certfile;
 6        ssl_certificate_key /some/path/to/certkey;
 7        
 8        root /some/pathto/blog;
 9        index index.html index.htm index.nginx-debian.html;
10}

Scenario-2: Redirecting all the requests from www to non-www domain

  1. Add below piece of new server block to your nginx config file which contains server blocks
 1# This is the block which will redirect the requests from www to non-www domain
 2# The port 443 is for https, you can update it to other port to serve for http
 3server {
 4        listen 443 ssl;
 5        listen [::]:443;
 6        server_name www.foo.com;
 7        ssl_certificate /some/path/to/certfile;
 8        ssl_certificate_key /some/path/to/certkey;
 9        return 301 $scheme://foo.com$request_uri;
10}

There should be a server block which would be serving non-www request for this to work for example some thing like below

 1server {
 2        listen 443 ssl;
 3        listen [::]:443;
 4        root /some/pathto/blog;
 5
 6        index index.html index.htm index.nginx-debian.html;
 7        ssl_certificate /some/path/to/certfile;
 8        ssl_certificate_key /some/path/to/certkey;
 9
10        server_name foo.com;
11}

In general using above examples you can redirect requests from non-www to www or from one domain to another. You will observe that in the example blocks I have used 301, this is to inform that the redirect is permanent. Hope this is helpful.