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\nserver {\n listen 80;\n listen 443 ssl;\n server_name www.example.com;\n ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;\n ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;\n return 301 https://example.com$request_uri;\n}
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\nRewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]\nRewriteRule ^ 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.