I have been trying to figure out for a while how to redirect the requests from the non-WWW domain to the WWW domain. This is the HTTPS.conf file:
server {
server_name domain.com *.domain.com;
return 302 https://$host$request_uri;
}
server {
listen 443 ssl default_server;
server_name www.domain.com;
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
}
Based on the configuration it should be working. As all non WWW domains should get redirected, but they don't. I have changed the 301 to 302 for testing purposes. These are the errors I get when I run nginx -t
nginx: [warn] conflicting server name "domain.com" on 0.0.0.0:80, ignored
nginx: [warn] conflicting server name "domain.com" on 0.0.0.0:80, ignored
nginx: [warn] conflicting server name "*.domain.com" on 0.0.0.0:80, ignored
nginx: [warn] conflicting server name "www.domain.com" on 0.0.0.0:443, ignored
This is the HTTP.conf file where the certificate is managed.
server {
server_name www.domain.com domain.com;
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed b$
ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed$
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.domain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = domain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 default_server;
server_name www.domain.com domain.com;
return 404; # managed by Certbot
}
I am sure that the issue is with the last few if lines that are generated by certbot. But if I change them/remove the domain.com from the port80 server block I end with "SSL certificate not valid". Probably because of the redirections. There are just too many factors here for me to be able to figure out the solution alone. I dont have issues with http to https redirect.