Search engines and cookies treat www.example.com and example.com as different sites. Pick one canonical host and permanently redirect the other.
www → apex (canonical is the bare domain):
# Redirect www to the apex domain.
server {
listen 443 ssl;
http2 on;
server_name www.example.com;
# ssl_certificate must also cover www.example.com (or use a wildcard / SAN cert).
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
http2 on;
server_name example.com;
# ...the real site...
}
apex → www (canonical is www) — just swap the hostnames:
server {
listen 443 ssl;
http2 on;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
Notes:
- Use
$request_uri(path + query), not$uri, so query strings survive. - The redirecting block still needs a valid certificate for that hostname, or browsers throw a TLS error before they ever see the redirect. A Let’s Encrypt cert with both names (or a wildcard) covers it.
- Don’t forget the port-80 → HTTPS redirect as well (see the HTTP→HTTPS recipe); the two compose — HTTP www first goes to HTTPS, then to the canonical host.
- There’s no SEO difference between choosing www or apex; just be consistent and set the same choice in your app and sitemap.
sudo nginx -t && sudo nginx -s reload