How to disable WWW prefix with nginx

Only idiots use “www” prefix for websites. So, if you are not one, you should not allow your users to visit your websites with this prefix. If you use nginx as your web server then it is very easy to configure redirection from any address of type www.site.com to just site.com. Nice? Yeah. All what you need is just to add one vhost:

server {
	listen 80;
	server_name ~^www\.(.+)$;
	set $target $1;
	rewrite ^(.*)$ http://$target$1 permanent;
}

If you want to configure disallowing www to only one selected host, use the following configuration:

server {
	listen 80;
	server_name www.some_server.web.id;
	rewrite ^(.*)$ http://some_server.web.id$1 permanent;
}

You may also configure your server to display an error page for everybody who tries to visit www.* on your server. You may replace 503 with any other standard HTTP error code.

server {
	listen 80;
	server_name ~^www\..+$;
	return 503;
}