3

I'm not sure if this has been answered before but I tried looking for it. Anyways, I'm currently developing a website but I would like to make the actual site content only accessible from my IP address. I then want .htaccess to redirect all other IP address to a separate file on my server. That one file would be called subscribe.php.

I've tried a couple things but nothing provided me with the result I wanted. I know my server allows .htaccess to be used since I've used it to change some other things such as preventing caches.

2

2 Answers 2

15

You can use mod_rewrite to do that. Add the following in your .htaccess file:

Code:

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !=123.45.67.89
RewriteRule index.php$ /subscribe.php [R=301,L]

Alternative solution:

<?php $allow = array("123.456.789", "456.789.123", "789.123.456"); //allowed IPs

if(!in_array($_SERVER['REMOTE_ADDR'], $allow) && !in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $allow)) {

    header("Location: http://domain.tld/subscribe.php"); //redirect

    exit();

} ?>

Hope this helps!

4
  • 1
    An attacker could simply set the X-Forwarded-For header and bypass this filter.
    – douggard
    Nov 29, 2015 at 2:39
  • I know the method isn't foolproof - those extra fields are arbitrary HTTP headers provided by the client, and anyone could easily spoof that. But do you have any better suggestions here? Nov 29, 2015 at 6:01
  • @douggard Any example about bypassing this HTTP_X_FORWARDED_FOR filter? I want to test my app's security.
    – Pathros
    Mar 8, 2016 at 16:47
  • Get a "modify headers plugin" for Chrome or Firefox. Set an X-Forwarded-For header to the IP address you allow. Visit the page from an IP not allowed. Really, you should just remove the X_FORWARDED_FOR check, unless you're usually going through a proxy.
    – douggard
    Mar 8, 2016 at 20:15
1

You can use mod_rewrite for the same.

Add following in your .htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^80\.40\.20\.[0-9]$ # your ip here
RewriteCond %{REQUEST_URI} !^/subscribe.php
RewriteRule .? /subscribe.php [R,L]
</IfModule>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.