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