Enabling and Forcing HTTPS on nginx server

Getting used to nginx. Just configured nginx to enable HTTPS and also force HTTPS by redirecting HTTP to HTTPS.

1. Get the SSL certs on the server – Navigate to /etc/ssl. Create your own directory with the domain name if you wish to or you could please your SSL Certs with the existing certs and private sub-directories under there. I preferred to create a new directory so it’s easy to manage the certs created by us. Place the following 2 files in the directory, e.g.

/etc/ssl/domain.com/20180521-domain_com.key
/etc/ssl/domain.com/20180521-domain_com.crt

2. Modify the nginx configuration – Navigate to /etc/nginx/sites-available. Open the file redash that is created during the server setup and add the following lines of code so the final file looks something like this (The pieces of code in Bold are the ones that were added).

upstream rd_servers {
  server 127.0.0.1:5000;
}

server {

  server_tokens off;

  listen 80;
  server_name hostname.domain.com;
  return 301 https://$server_name$request_uri;

  access_log /var/log/nginx/rd.access.log;

  gzip on;
  gzip_types *;
  gzip_proxied any;

  location / {
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass       http://rd_servers;
  }
}
server {

  server_tokens off;

  listen 443;
  server_name hostname.domain.com;

  ssl on;
  ssl_certificate /etc/ssl/domain.com/20180521-domain_com.crt;
  ssl_certificate_key /etc/ssl/domain.com/20180521-domain_com.key;
  ssl_protocols TLSv1.2;

  access_log /var/log/nginx/rd.access.log;

  gzip on;
  gzip_types *;
  gzip_proxied any;

  location / {
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass       http://rd_servers;
  }
}

The following lines of code will redirect the HTTP traffic to HTTPS. Only required if you completely want to disable HTTP.

return 301 https://$server_name$request_uri;