Nginx Logo

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.,, 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:

server {
  listen 80;
  listen [::]:80;
  add_header X-Frame-Options "SAMEORIGIN";

  return 301$request_uri;

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:

server {
  listen 80 default_server;
  listen [::]:80 default_server;
  server_name _;

  return 301$request_uri;

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:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^$
RewriteRule ^(.*)$$1 [L,R=301]

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.

RewriteEngine on
RewriteCond %{SERVER_NAME} !
RewriteRule ^{REQUEST_URI} [END,NE,R=301]
Profile Photo for Anthony Heddings Anthony Heddings
Anthony Heddings is the resident cloud engineer for LifeSavvy Media, a technical writer, programmer, and an expert at Amazon's AWS platform. He's written hundreds of articles for How-To Geek and CloudSavvy IT that have been read millions of times.
Read Full Bio »