How to Redirect Website IP to Domain Without Using .htaccess

When running a website on its own IP, you should be aware that visitors can access it through your domain name or directly via the IP address.

For example, if your site is example.com and its IP address is 111.222.33.444, a user could visit your “About Us” page by typing either example.com/about or 111.222.33.444/about. While this might seem like a minor detail, it can actually harm your SEO and leave your site vulnerable to security risks. You want users to access your site only through the domain.

Why not .htaccess 

To fix the problem, most people suggest adding a redirect rule in the .htaccess file, such as:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^111.222.33.444
RewriteRule (.*) https://example.com/$1 [R=301,L]

While this method works for redirecting the IP address to the root domain, your subpages can still be accessed via the IP address, leaving the back door wide open.

Effective Solutions for Redirecting IP to Domain

After exploring various solutions, I’ve found two methods that work effectively, whether you’re using WordPress or a different platform.

  • Using wp-config.php – for WordPress Users

If you’re running a WordPress site, you can easily redirect IP access to your domain by adding the following code to your wp-config.php file, just before this line (require_once ABSPATH . ‘wp-settings.php).

// Redirect IP address to a similar page, including subpage — 111.222.33.444/contact redirects to example.com/contact

if($_SERVER[‘SERVER_NAME’] != ‘example.com’){
$redirect_url = ‘https://example’ . $_SERVER[‘REQUEST_URI’];
header(‘Location: ‘ . $redirect_url);
exit;
}

  • Using Index.php – For Non-WordPress Users

If you’re not using WordPress, you can achieve the same result by adding the above code to your index.php file. This file is usually located in your website’s root folder or the public_html directory. If the file doesn’t exist, you can create it. Then, add the code above at the very top of the index.php file:

  • Redirecting All IP Address Access to the Homepage

If you prefer to redirect all IP access, including subpages, to your homepage instead of the corresponding sub-page, you can use the following code:

// Redirect IP to the homepage — 111.222.33.444/contact redirects to example.com

if($_SERVER[‘SERVER_NAME’] != ‘example.com’){
header(‘location: https://example.com’);
exit;

With this code, anyone who tries to visit 111.222.33.444/about will redirect to your homepage at example.com

This code restricts your content’s access to your domain.

Last updated on

by

Published In

Leave a Comment

Your email address will not be published. Required fields are marked *

Editors Pick

css.php