'retrun' is recommended rather than 'rewrite'.
server { listen 80; server_name example.com; return 301 https://www.example.com$request_uri; } server { listen 443 ssl; . . . }
# http://www.example.com --> https://example.com server { listen 80; server_name www.example.com; return 301 https://example.com$request_uri; } # https://www.example.com --> https://example.com server { listen 443 ssl http2; server_name www.example.com; ssl on; ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem; return 301 https://example.com$request_uri; } # http://example.com --> https://example.com server { listen 80; server_name example.com; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name example.com; ssl on; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; . . }
server { listen 80; server_name www.example.com example.com; if ($http_host = example.com) { rewrite (.*) http://www.example.com$1 permanent; } . . }