Skip to content
TrySitePrice

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

Best/Tutorial

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 {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}

  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.
rnNote: You need to replace /path/to/cert.pem and /path/to/key.pem with the actual paths to your SSL certificate and private key.