HTTPS and no www with Nginx

I have tried to find the most efficient way to redirect all trafic for a specific domain to its https counterpart, and also to redirect to the domain without the www subdomain.

I'm using Nginx in production and after combining various different solutions I found, I settled on this simple configuration that I now use and that I think is quite straightforward and efficient. Thought I'd share, for what it's worth.

(In this example the backend is a PHP application located in /var/www/my-website/ and I'm using letsencrypt for the certificates)

# no SSL
# Redirect both urls to the http server block
server {
        return 301$request_uri;

# The main block : SSL
server {


        # If it has a www, rewrite.
        # The 'last' here is important
        # because we are cautious with the 'if's
        if ($host ~* ^www\.){
            rewrite ^(.*)$$1 last;

        include ssl.conf;

        ssl_certificate /etc/letsencrypt/live/;
        ssl_certificate_key /etc/letsencrypt/live/;

        # Application-specific stuff, just for illustrating
        index index.php;
        root /var/www/my-website;

        location / {
          # try to serve file directly, fallback to app.php
          try_files $uri /index.php$is_args$args;

        # Pass on to FPM
        location ~ \.php$ {
           include php-fpm.conf;

        # Deny access to .ht* files
        location ~ /\.ht {
          deny all;

ssl.conf is as follows (of course, you might need to create the /etc/ssl/certs/dhparam.pem file beforehand, with sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048):

listen 443 ssl;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_stapling on;
ssl_stapling_verify on;
add_header Strict-Transport-Security max-age=15768000;

And, for reference, php-fpm.conf is available here