How to Redirect IP Request to Domain in Apache

redirect ip request to domain in apache

Sometimes, you may want to block or redirect direct IP requests to your site, for SEO or security purposes. You can easily redirect IP request to domain in Apache web server using .htaccess file, which allows you to modify Apache server configuration without accessing its config file. So let us take a look at how to redirect IP request to domain in Apache.


How to Redirect IP Request to Domain in Apache

Here are the steps to redirect IP request to domain in Apache.

Before you proceed, please ensure that you have enabled .htaccess (mod_rewrite) in Apache. If not, then here’s how you can do it:


Place your .htaccess file in the root document folder of your website (/var/www/html).


1. Open .htaccess file

Open .htaccess file in a text editor

$ sudo vim /var/www/html/.htaccess


2. Redirect IP request to domain

Let’s say you run a website with domain and its IP address is Now you want to redirect all requests to to We will use Apache’s mod_rewrite module for this purpose. It allows you to easily redirect/rewrite URLs based on specific conditions.

In that case, add the following lines to your .htaccess file

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

In the above code, the first line enabled mod_rewrite if not done already. We use a RewriteCond directive to match URLs that contain your IP address. The last line redirects all matching URLs.

Update the IP address and domain name in the above code, as per your requirement.


3. Restart Apache web server

Restart Apache web server to apply changes

$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]


That’s it! Now Apache will automatically redirect all direct IP requests to your domain.



About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!