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.

Nart Barileva
  • 1,083
  • 2
  • 9
  • 10
  • RTFM: http://httpd.apache.org/docs/current/howto/access.html – Marc B Jul 17 '13 at 16:14
  • Thanks for your answer :p The link seemed to have the details I was looking for but I have no idea how to use it for my specific case :s I'm still pretty new to Apache and `.htaccess` – Nart Barileva Jul 17 '13 at 16:20

2 Answers2

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!

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • 1
    An attacker could simply set the X-Forwarded-For header and bypass this filter. – douggard Nov 29 '15 at 02: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? – Amal Murali Nov 29 '15 at 06:01
  • @douggard Any example about bypassing this `HTTP_X_FORWARDED_FOR` filter? I want to test my app's security. – Pathros Mar 08 '16 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 08 '16 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>
Sumoanand
  • 8,835
  • 2
  • 47
  • 46