Redirect www to non-www in Tengine

2026-09-30

Having both www.yourdomain.com and yourdomain.com serve content splits your link equity and can duplicate pages in search results. Pick one canonical form and 301-redirect the other. Here is the Tengine pattern, which also handles the HTTPS hop cleanly.

Step 1 — The redirect server block

Put this block before your main site block, listening on both ports:

server {
    listen 80;
    listen 443 ssl http2;
    server_name www.yourdomain.com;

    ssl_certificate     /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;

    return 301 https://yourdomain.com$request_uri;
}

Two details that matter:

Step 2 — The opposite direction

If you prefer www as canonical, swap the server_name and target:

server {
    listen 80;
    listen 443 ssl http2;
    server_name yourdomain.com;
    return 301 https://www.yourdomain.com$request_uri;
}

Step 3 — Keep the canonical consistent

Verify

curl -I https://www.yourdomain.com/post/1

You should see 301 Moved Permanently with location: https://yourdomain.com/post/1. Do the same check on plain http://.

Summary

One server block, a 301 with $request_uri, and consistent canonicals — that is the whole fix. Redirects are rewrite territory, so if you also battle silent rewrite failures, my rewrite troubleshooting guide covers the usual suspects.

Related articles