How to set HTTPS on website using Nginx and CloudFlare as CDN

First of all, you have to add correct settings in Cloudflare under the SSL/TLS tab. Make sure it is set to Full if using self-generated/certbot generated certificate or else Full Strict if using Cloudflare provided certificate. Once the settings have been done from Cloudflare, move to Nginx configuration of the website and set them like this:

server {

       listen 80;

       listen [::]:80;

       server_name example.com www.example.com;

       return 301 https://example.com$request_uri;

 

}

server {

        listen 443 ssl;

        listen [::]:443 ssl;

        server_name www.example.com;

        ssl on;

        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;

        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        return 301 https://example.com$request_uri;

}

server {

        listen 443 ssl;

        listen [::]:443 ssl;

        server_name example.com;

        ssl on;

        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;

        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        root /var/www/html/example.com;

        index index.html;

 

        location / {

                try_files $uri $uri/ =404;

        }

}

 

First server block ensures redirection to HTTPS and 2nd makes sure non-www is redirected to www. You can modify them as per you convenience.  Avoid automatic NGINX redirections settings done by Certbot if using Cloudflare.

Tags