Nginx Make website inaccessible via IP

I've got my website set up to be accessible via example.com. If possible I want to prevent it from being accessed via its IP altogether or at least 301 redirect it to website.

Is the former possible and if yes, how?


You must create a default vhost configuration file and include it before of others.

For example you can save this default config to /etc/nginx/conf/default.conf:

server {
    listen 80 default_server;
    return 444;
}

And include it in nginx.conf:

http {
....
 include "/etc/nginx/conf/default.conf";
 include "/etc/nginx/vhosts/*.conf";

}

Be sure that it is included before other vhosts' configurations.