Redirects & rewrites

Redirect www to apex (or apex to www)

2 min · updated June 16, 2026

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:

sudo nginx -t && sudo nginx -s reload

← All snippets