Apache – Redirect IP to URL

When you enter your server’s IP address in the browser address bar, you are in fact sending an HTTP request over TCP/IP to your server with the URL field equal to http://IP. It is recommended that you redirect this request to your domain.

So, without further ado, let’s redirect IP to domain using htaccess

Configure apache

You need to allow apache configuration override. Open the apache configuration file for the site.

In this guide I will be using the default site hosted at “/var/www/html” but you may be hosting your site from a different directory (e.g. /var/www/CoolDomainName.com/”).

Open the apache config file for your site with any text editor.

sudo vim /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
ServerAdmin webmaster@localhost 
DocumentRoot /var/www/html 
ErrorLog ${APACHE_LOG_DIR}/error.log 
CustomLog ${APACHE_LOG_DIR}/access.log combined 
</VirtualHost>

In order to allow configuration using .htaccess files, you now need to allow override in the server configuration. This is done with the following lines:

Note: remember to substitute the root directory with your website’s directory. Do not copy and paste this snippet if you are not using the default directory.

<Directory /var/www/html>
AllowOverride All
</Directory>

After you paste the configurations in the right place, your site’s config file should look something like this.

<VirtualHost *:80>
ServerAdmin webmaster@localhost 
DocumentRoot /var/www/html 
<Directory /var/www/html>
AllowOverride All
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log 
CustomLog ${APACHE_LOG_DIR}/access.log combined 
</VirtualHost>

Create a new or open the existing .htaccess file in the site’s root directory. In our example we are using the default directory.

sudo vim /var/www/html/.htaccess

We want to add a few lines to the .htaccess file that contain the redirection rule.

The rule basically means that if the server recieves a request with the URL http://X.X.X.X where X.X.X.X is the servers IP. Redirect this request to https://site.domain.name with status 301

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^X\.X\.X\.X$
RewriteRule ^(.*) https://site.domain.name/$1 [L,R=301]

An actual example would look like

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^192\.1\.1\.32$
RewriteRule ^(.*) https://mysite.com/$1 [L,R=301]

Leave a Comment