How to redirect Nginx non-www to www domain over SSL

To redirect a non-www domain to a www domain over SSL in Nginx, you need to configure a server block in your Nginx configuration file. Here’s an example of how to do it:

  1. Open the Nginx configuration file in a text editor:
sudo nano /etc/nginx/nginx.conf
  1. Add the following code to the file, replacing example.com with your actual domain name:
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/key.pem;
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/key.pem;

location / {
# Your site configuration goes here
}
}

  1. Save the changes and close the file.
  2. Test the Nginx configuration for syntax errors:
sudo nginx -t
  1. If the test is successful, reload Nginx to apply the changes:
sudo systemctl reload nginx
  1. Now, when you access http://example.com, Nginx will redirect to https://www.example.com, and the SSL certificate will be used to secure the connection.

Note: You need to replace /path/to/cert.pem and /path/to/key.pem with the actual paths to your SSL certificate and private key.

Leave a Comment