NGINX – Redirecting HTTP to HTTPS

Using HTTPS is highly recommended and I cannot stop when explaining the benefits of using it! Also something which is more important is to make sure when HTTPS is setup it is ensured that all traffic via HTTP is blocked in a way that it is redirected to HTTPS. This can be easily achieved by giving NGINX the following set of instructions in the virtual server configurations.

Begin by setting up the virtual server for your application so that a domain name points to it. A simple virtual server configuration using SSL is as follows

server {
 listen 443 ssl;
 server_name example.com;
 
 ssl_certificate /path/to/your/example.com.crt;
 ssl_certificate_key /path/to/your/example.com.key;

 root /path/to/your/content;
 index index.html;
 include /etc/nginx/mime.types;
}

Other NGINX blogs you might find useful

  1. NGINX – Load Balancing your application made simple
  2. NGINX – Redirecting traffic between www and non-www domain
  3. NGINX – Restrict access to Geographical Locations using GeoIP module
  4. NGINX – Disable direct access (via http and https) to a website using IP address
  5. NGINX – Easiest way to setup SSL on using .pfx files
  6. NGINX – Understanding and Setting up a reverse proxy server

Now setup the redirect from HTTP to HTTPS using:

server {
 listen 80;
 server_name example.com;
 return 301 https://example.com$request_uri;
}

this redirects http://example.com to https://example.com along with the URI in the request using the return directive and status code 301. For example,

http://example.com/user/1 would be redirected to https://example.com/user/1.

knoldus-advt-sticker

Written by 

Sidharth is a Lead Consultant, having experience of more than 4.5 years. He has started working on Scala and Clojure and is actively involved in other developmental work. He enjoys working in a team and believes that knowledge is something that should be shared openly and on a large scale. As an avid gamer and passionate player, he likes to be involved in both indoor and outdoor activities.

6 thoughts on “NGINX – Redirecting HTTP to HTTPS

Leave a Reply

%d bloggers like this: