Both work. What harms a site is serving the same content at both addresses, or redirecting through two or three hops before arriving. Choose one, send everything else to it in a single redirect, and be done.
Nginx
# a small server block whose only job is the redirect
server {
listen 80;
listen 443 ssl;
server_name www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
return 301 https://example.com$request_uri;
}
The certificate must cover BOTH names, or the redirect from https://www fails with a warning before it can redirect. Issue it for example.com and www.example.com together.
Apache and LiteSpeed
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]
One hop, not three
A common accident is http://www redirecting to https://www, then to https://example.com. Every hop is a full round trip. Do it in one.
curl -sSIL https://www.example.com/page | grep -E '^HTTP|^location'
Read that output: you want exactly one 301 and then a 200. Two 301s means there is a redirect to remove.
Then make the site agree
- The site URL setting in your application.
- The canonical tag on every page.
- The sitemap.
- Anything hard-coded in the content.
If you have no reason to prefer one, use the bare domain: it is shorter, and it is what people type. The one real argument for www is that a bare domain cannot be a CNAME, which matters if you ever need to point the apex at a service that requires one.