How to Redirect IP Request to Directory in Apache


redirect ip request to directory in apache

Sometimes, you may need to redirect request to your IP address, to a specific directory. You can easily do it in Apache web server using .htaccess file, that allows you to modify web server settings without actually accessing server configuration file. Let us take a look at how to redirect IP request to directory in Apache.

 

How to Redirect IP Request to Directory in Apache

Here are the steps to redirect IP request to directory 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 URL

Let’s say you have a website www.example.com and its IP is 54.54.54.54. You want to redirect all requests to this IP, to www.example.com/product/ directory. For example, you want to redirect request to 54.54.54.54/login.php to www.example.com/product/login.php

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

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^54\.54\.54\.54$
RewriteRule ^(.*)$ http://www.example.com/product/$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 to your directory and retains the URL string after IP address.

If you don’t want to retain that string, simply remove ‘/$1’ in the above code.

Update the IP address, domain name and directory 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’t it! Now Apache web server will automatically redirect all requests to your IP to your specific directory.

 

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!