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.

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