December 17, 2020

Enable SSL using Nginx and Cloudflare

Enable SSL using Nginx and Cloudflare

Cloudflare is a service that sits between the visitor and the web server, acting as a reverse proxy for websites. Cloudflare provides a Content Delivery Network (CDN), as well as DDoS mitigation and distributed domain name server services. Cloudflare provide free SSL certificate for personal web sites and it's very easy to setup.

GENERATING CERTIFICATE

Step 1: Create an account on Cloudflare

Enter your information and then click on ‘Create Account’

Step 2: Configure your website/domain

Enter the site here

addsite-1

Step 3: Select a CloudFlare Plan

Step 4: Configure your Website DNS Records

Once the scan is done, you will see an orange cloud next to your main domain. That means the configuration is correct. Mail and FTP are bypassed by Cloudflare and should show grey clouds.

dns1

Step 5: Update your NameServers

You need to point your NameServers to Cloudflare. To do this you would have to log into your domain registrar account, find the setting to change the NameServer.

Step 6: Origin Certificates

Generate a free TLS certificate signed by Cloudflare to install on your origin server.

cert1-1

Click Next and you will see a dialog with the Origin Certificate and Private key. You need to transfer both the origin certificate and private key from CloudFlare to your server.

Step 7: Redirect traffic to HTTPS

You need to add www.mywebsite.com/* and mywebsite.com/* separately, and for each of these URL patterns select ‘Always Use HTTPS’.

CONFIGURE NGINX FOR SSL

modify the Nginx configuration file to do the following:

  • Listen on port 80 and redirect all requests to use https.
  • Listen on port 443 and use the origin certificate and private key that you added in the previous section.

Modify the file so it looks like the following:

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

server {
	    server_name example.com www.example.com;
	    listen 443 ssl;
	    server_tokens off;

	location / {
		    proxy_pass	http://ghost:2368;
	        proxy_set_header    X-Real-IP $remote_addr;
	        proxy_set_header    Host      $http_host;
		proxy_set_header X-Forwarded-Proto https;
	        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	}
	ssl_certificate     /etc/nginx/conf.d/ssl/cert.pem;
	ssl_certificate_key 	/etc/nginx/conf.d/ssl/key.pem;
}