NGINX – Redirect IP address to domain name

NGINX – Redirect IP address to domain name

When you are hosting a site on AWS, GCP or Azure, always make sure you get a static IP or Elastic IP as AWS likes to call it.

There are many reasons to get a static IP that we won’t get into in this article but if google pings the ip of your website and gets a 200 response, it is going to start crawling it and before you know you will have 1M pages in Google. (Happened with our client) (Yes we build React/Node apps for our clients too) and yes Google will show those results in SERP. Problem is when your IP is public, bots will discover them and they are gonna start pinging all these pages and putting immense load on your server and you’ll keep wondering why page loads are taking so much time and why your server has such high CPU or RAM usage.

When these bots or google ping or visit the IP address directly, the request doesn’t go through your CDNs like cloudfront or cloudflare(much better) and that only makes it worse.

So before its too late or before you even publish a site make sure ip addresses are redirected to domain

So how can we achieve that using NGINX

Here is a simple snippet that should do the job

server {
    listen 80;
    server_name xx.xx.xx.xx;
    return 301 $scheme://$request_uri;