Nginx by examples: HTTPS

Setting up SSL/TLS on Nginx is a very simple exercise. A typical setup will look like this:

server {

  root /var/www/mydomain.com/web/;
  index index.php;

  server_name mydomain.com;

  # we enable SSL
  listen 443 ssl;
  ssl_certificate /home/ubuntu/ssl/mydomain.com.chained.crt;
  ssl_certificate_key /home/ubuntu/ssl/mydomain.com.key;

  # we enable only more recent protocols
  ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;

  # as suggested by Nginx we prioritize newer ciphers
  ssl_ciphers  HIGH:!aNULL:!MD5;

  # we cache the ssl session parameters 
  # to reduce the CPU load on the web server
  ssl_session_cache   shared:SSL:10m;
  ssl_session_timeout 10m;

  # we increase the keep alive timeout
  # to improve socket reuse and reduce
  # the need for SSL handshakes
  keepalive_timeout 70;

  access_log /var/www/mydomain.com/log/mydomain.com.access;
  error_log /var/www/mydomain.com/log/mydomain.com.error error;

  location / {

    # no static file serving here
    # all non /api calls will return 403
    deny all;

  }

  location /api {
    proxy_pass http://127.0.0.1:8080;
  }

}

 Http to https redirect

More commonly you would want to redirect all http:// traffic to https://. Luckily this can be achieved quite easily by pre pending another server block to do the redirect for all http requests:

server {
  # we listen to http:// requests
  listen 80;

  # we respond to the same domain as the https block
  server_name mydomain.com;

  # we return a 301 to the very same URL with https://
  # GET parameters are preserved
  return 301 https://$server_name$request_uri;
}

server {

  root /var/www/mydomain.com/web/;
  index index.php;

  server_name mydomain.com;

  # we enable SSL
  listen 443 ssl;
  ssl_certificate /home/ubuntu/ssl/mydomain.com.chained.crt;
  ssl_certificate_key /home/ubuntu/ssl/mydomain.com.key;

  # the rest as before...
}

 Notes

 
2
Kudos
 
2
Kudos

Now read this

Evolving CRUD (part 1)

Serving content at scale limiting complexity Scalability is a simple concept that proves difficult to achieve without introducing complexity Create Read Update Delete CRUD stands for Create Read Update Delete and identifies all the... Continue →