Paulund

Nginx Redirect www to non-www

It's very common these days to see websites that just use the non-www domain and therefore redirect all requests to www to the domain.

Below is a quick code snippet you can use to take all requests to www on either http or https and redirect them to the non-www domain.

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

This will listen on both port 80 and 443 for requests to www and perform a 301 redirect to the domain without www.