How to Redirect IP Request to URL in Apache


redirect ip request to url in apache

Sometimes, you may need to redirect request to your IP address, to a specific URL. 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 URL in Apache.

 

How to Redirect IP Request to URL in Apache

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

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-page [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 the specific URL.

If you want to retain the query string in your request, use ‘$1’ at the end of redirection

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^54\.54\.54\.54$
RewriteRule ^(.*)$ http://www.example.com/product-page/$1 [L,R=301]

Update the IP address, domain name and URL 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 URL.

 

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!