How to redirect to or from www
Pick one canonical form of your domain - either www.example.com or example.com - and redirect the
other to it. This avoids duplicate content and keeps links and analytics consistent.
Before you start
-
SSH access to the host - see SSH access.
-
Both forms should point to your server and have a certificate (
cert_type: letsencrypt) so HTTPS works after the redirect - see TLS certificates. -
Add the rule to
~/nginx/20rewrites.conf- see custom Nginx configuration.
Redirect non-www to www
if ($host ~ ^(?!www\.)(?<domain>.+)$) {
return 301 $scheme://www.$domain$request_uri;
}
Redirect www to non-www
if ($host ~* ^www\.(?<domain>.+)$) {
return 301 $scheme://$domain$request_uri;
}
Redirect extra domains to your main domain (keeping the path)
if ($host ~* "(old-one\.example\.net|old-two\.example\.org)$") {
return 301 $scheme://www.example.com$request_uri;
}
Add a trailing slash to a path
Redirect a path without a trailing slash to its slashed form, so a single canonical URL is served:
location /blog {
rewrite ^/blog$ /blog/ permanent;
}
Redirect a domain to a specific page
Send every request for one domain to a fixed page on another, rather than keeping the requested path:
if ($host ~* "^.*your-domain\.be$") {
rewrite ^/$ https://your-domain/page/ redirect;
}
Apply and verify
tscli nginx reload
Check the redirect (look for 301 and the Location header):
curl -I https://example.com
If it did not work
A redirect loop means both rules are present, or the application adds a redirect of its own -
keep one. No 301 at all means the rule is in a file Nginx does not load; it reads
~/nginx/*.conf only. It can also mean tscli nginx reload refused the rule; its output names the
line. A redirect to the wrong scheme means one form of the domain has no certificate yet - see
TLS certificate problems, or
contact support.