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:
- Open the Nginx configuration file in a text editor:
sudo nano /etc/nginx/nginx.conf- Add the following code to the file, replacing
example.comwith your actual domain name:
server {
listen 80;
server_name example.com;
return 301 https://www.example.com$request_uri;
}server {rnlisten 443 ssl;rnserver_name example.com;rnssl_certificate /path/to/cert.pem;rnssl_certificate_key /path/to/key.pem;return 301 https://www.example.com$request_uri;rn}server {rnlisten 443 ssl;rnserver_name www.example.com;rnssl_certificate /path/to/cert.pem;rnssl_certificate_key /path/to/key.pem;
location / {# Your site configuration goes herern}rn}
- Save the changes and close the file.
- Test the Nginx configuration for syntax errors:
sudo nginx -t- If the test is successful, reload Nginx to apply the changes:
sudo systemctl reload nginx- Now, when you access
http://example.com, Nginx will redirect tohttps://www.example.com, and the SSL certificate will be used to secure the connection.
/path/to/cert.pem and /path/to/key.pem with the actual paths to your SSL certificate and private key.