no-www for nginx

If you happen to be in no-www camp and want to redirect people accessing www.whateverdomain.com to the no-www version but have lots of domain, instead of writing one by one and you’re not keen in using config generator (I’m not), you can use this:

server {
  listen 80;
  listen [::]:80 ipv6only=on;
  server_name ~^www.(?<domain>.+)$;
  rewrite ^ $scheme://$domain$request_uri? permanent;
  access_log /var/log/nginx/access-no_www.log;
}

Remove listen [::]:80 ipv6only=on; if you’re not using IPv6 and adjust the log file path to wherever you want (or just turn off or remove it altogether).

Note that this trick doesn’t work well with HTTPS/SSL domains since you’ll get big fat warning about incorrect domain name in certificate or about self-signed certificate if you’re using wildcard one.

Leave a Reply

Your email address will not be published. Required fields are marked *