Non-www to www & https redirect
If I understand correctly, then you want to force non www to www. And you want to force all requests to https. This config code checks if the $host
start with "www."
or not. If it does not, then nginx will add "www."
before the $host
then return the correct https location. It will work with subdomains as well.
server {
if ($host !~* ^www\.) {
# if host name starts with (case insensitive) "www."
return 301 https://www.$host$request_uri;
}
if ($host ~* ^www\. ) {
# if host name doesn't start with (case insensitive) "www."
return 301 https://$host$request_uri;
}
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 404;
}
Possibly better way with Certbot
You can automatically produce the code you need by using Certbot. It will also help you manage certificates a lot and automate renewal. But Certbot will not change non-www to www, you'll have to edit auto-generated config to look like the config above. The other difference is that you will be expected to have different config blocks/files per domain, but not sure if necessary. This is what the default config looks like per domain.
server {
if ($host = www.yourdomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = yourdomain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
server_name yourdomain.com www.yourdomain.com;
return 404; # managed by Certbot
}
I think it's best practice to separate the config files for each domain and subdomain and use the default Certbot format until you have understood Nginx more. This way you can disable the redirect of non-www to www very easily. The default code above from Certbot, would be what you would put when you don't want to redirect in that case. Long term this makes more sense to me, but I understand when users are more comfortable with www or other parts of the website might need the www.