How to redirect non-www to www HTTP / TLS /SSL traffic on Nginx

Here is a simple Nginx configuration to redirect non-www traffic to www with HTTPS:

server {
listen 80;
server_name example.com;
return 301 https://www.example.com$request_uri;
}

server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/cert.key;
return 301 https://www.example.com$request_uri;
}

server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/cert.key;
# Add your website configuration here
}

 

Make sure to replace example.com with your own domain name and update the paths to the SSL certificate and key files.

Leave a Comment