Learn Redirect HTTP Requests To HTTPS On Nginx

January 29, 2020

Table of Contents

    Introduction

    This writeup shows you how to setup Nginx to redirect non-secure (http) requests to secure (https) ones.

    Pre-requisites

    • You have An ITWeb.Services Linux instance running Nginx.
    • Your have domain name (e.g example.com) whose DNS A records for “@” and “www” are pointing to the IP of your IT Web Services machine above.
    • Ideally you should also have SSL setup on your instance.

    Setup redirect

    Add an additional server block to your vhost setting so it looks similar to below:

    server {
        listen 80;
        server_name example.com www.example.com;
        return 301 https://example.com$request_uri;
    }
    
    server {
        listen 443 ssl;
        server_name example.com;
    
        ssl_certificate     /path/to/cert-crt.crt;
        ssl_certificate_key /path/to/cert-key.key;
        #other site settings go here (e.g. ssl, logs, site root)
    }
    

    Need help?

    Do you need help setting up this on your own service?
    Please contact us and we’ll provide you the best possible quote!