It’s an edge case, but if someone types in your IP address instead of your domain name, you’ll want your server to handle that request properly, and redirect them to the actual site. We’ll show how to set it up in NGINX and Apache.
Why Is This Necessary?
For nearly every request, users are likely coming in using your domain name, so you won’t really see this issue in practice. But, it’s an easy fix, and doesn’t hurt to add.
You can set up your server to specifically listen on your IP address and return a 301 redirect to your real name, which will fix the issue and put your website name in the URL bar for any IP address-only requests.
However, a better and more complete method is to simply handle all other routes by returning a redirect. This way, any users sent to your IP address from anywhere (even with wrong host headers) will get redirected. For instance, if you wanted to point alternate spellings of your domain (i.e., howtogreek.com), to your real domain, this default redirect works as well.
Setting Up a Default Route In NGINX
If you simply want to listen on the IP, you can use the following configuration, which returns a 301 redirect for requests made specifically to the IP:
However, you can specifically listen for non-matches using server_name _, which only matches if no other rule does. You can return a 301 redirect in the same fashion:
Of course, as with any 301 redirect, you should first test with temporary 302 redirects to ensure your configuration is correct.
Setting Up a Default Route in Apache
In Apache, you can redirect IP requests to your domain name by adding a rewrite rule that matches for the IP:
If you want to redirect all other requests, you can do so by matching everything that isn’t your domain name, though be careful that this doesn’t conflict with any subdomains.