# 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](../../platform/hosts/ssh.md).
- Both forms should point to your server and have a certificate (`cert_type: letsencrypt`) so HTTPS
  works after the redirect - see [TLS certificates](../../platform/hosts/applications/tls-certificates.md).
- Add the rule to `~/nginx/20rewrites.conf` - see [custom Nginx configuration](configure.md#custom-nginx-configuration).

## Redirect non-www to www

```nginx
if ($host ~ ^(?!www\.)(?<domain>.+)$) {
    return 301 $scheme://www.$domain$request_uri;
}
```

## Redirect www to non-www

```nginx
if ($host ~* ^www\.(?<domain>.+)$) {
    return 301 $scheme://$domain$request_uri;
}
```

## Redirect extra domains to your main domain (keeping the path)

```nginx
if ($http_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:

```nginx
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:

```nginx
if ($http_host ~* "^.*your-domain\.be$") {
    rewrite ^/$ https://your-domain/page/ redirect;
}
```

## Apply and verify

```bash
tscli nginx reload
```

Check the redirect (look for `301` and the `Location` header):

```bash
curl -I https://example.com
```

## Related

- [Configure Nginx](configure.md)
- [TLS certificates](../../platform/hosts/applications/tls-certificates.md)
- [Connecting your domain](../../getting-started/connecting-your-domain.md)
