Remove www from URL with nginx

So I’ve recently been wearing my sysadmin hat, having installed and configured nginx a coworker showed me that if you added www as a subdomain the website was gone. Not good, so I did some googling and found a few examples on how to ensure users are redirected to the appropriate subdomain (or lack thereof).

The best solution is adding a server block in your nginx config file that returns a 301 permanent redirect. If you're using ubuntu it is most likely in /etc/nginx/sites-enabled.

server {
    return 301 $scheme://$request_uri;

Now you can reload the nginx config without causing downtime. In ubuntu:

sudo service nginx reload