How to redirect ssl www to ssl non-www in nginx

I recently got my beta access with https://letsencrypt.org/ and wanted to make sure my SSL is enabled for all traffic to my blog, so I figured I can easily rewrite non ssl traffic using www or non-www to send everyone to one consistent URL which is the non-www with SSL.

You can use this simple virtual.conf

server {  
    listen      80;
    server_name alicoding.com;
    rewrite     ^   https://$server_name$request_uri? permanent;
}


server {  
    listen 443 ssl;
    server_name alicoding.com;

    ssl_certificate        /etc/letsencrypt/live/alicoding.com/fullchain.pem;
    ssl_certificate_key    /etc/letsencrypt/live/alicoding.com/privkey.pem;
    if ($host = www.$server_name) {
      rewrite ^(.*) https://$server_name$request_uri? permanent;
    }
}

Let me explain what's going on here...

server {  
    listen      80;
    server_name alicoding.com;
    rewrite     ^   https://$server_name$request_uri? permanent;
}

This block basically listen to any non SSL traffic (http) and redirect to https:// and try to preserve the request_uri at the end.

For the second part you can ignore everything and just look at the magic here:

  if ($host = www.$server_name) {
    rewrite ^(.*) https://$server_name$request_uri? permanent;
  }

What happen here is that we are checking for any requested URL with www and redirect them to non-www version with ssl version enabled.

If you have any question hit me on twitter @alicoding :)