9

We have a directory on our site which we only want to be accessible by a couple of IP addresses. So we have this .htaccess file to try and get it working:

RewriteEngine on
RewriteCond %(REMOTE_ADDR) !^123\.123\.123\.123
RewriteCond %(REMOTE_ADDR) !^124\.124\.124\.124
RewriteCond %{REMOTE_ADDR} !^125\.125\.125\.125
RewriteCond %{REMOTE_ADDR} !^126\.126\.126\.126
RewriteCond %{REMOTE_ADDR} !^127\.127\.127\.127
RewriteCond %{REMOTE_ADDR} !^128\.128\.128\.128

RewriteCond %{HTTP_REFERER} !^http://www\.example\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://example\.com/ [NC]

RewriteRule ^.*$ http://www.example.com [R=301,L]

What we want it to do is, if the request does NOT come from one of our IP addresses (obviously changed them in the code above just for examples sake), or the referrer is not coming from a specific site, then redirect them elsewhere.

For some bizarre reason, it works for the IP which is in the position of the 126.126.126.126 one, but doesn't work for the others. Really can't figure out why it would be any different depending on the IP. What could be going wrong?

I'm aware this poses a security issue as the referrer can be spoofed, but we'll be coming up with a better solution soon, this is just a temporary measure.

BT643
  • 3,495
  • 5
  • 34
  • 55
  • Have you used the same browser? Haven't you entered the site URL in browser address bar itself ? (the referer would be empty then) – Nicolas Aug 09 '13 at 12:14
  • I've tried fresh browsers to make sure it's not a caching issue. And it *should* work directly typing the URL into a fresh browser window. It works for one of the IP addresses fine that way. The referrer is only needed if none of the IPs match. So if they're (NOT from IP1 AND NOT from IP2 AND NOT from IP3... AND the referrer isn't coming from x site, then get rid of them). – BT643 Aug 09 '13 at 12:47

2 Answers2

18

Forgot to post the answer to this. It was just a typo in the end.. DOH!

If you notice, some of the %{REMOTE_ADDR} lines have curly brackets, and some have normal brackets! They all needed curly ones.

RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123
RewriteCond %{REMOTE_ADDR} !^124\.124\.124\.124
RewriteCond %{REMOTE_ADDR} !^125\.125\.125\.125
RewriteCond %{REMOTE_ADDR} !^126\.126\.126\.126
RewriteCond %{REMOTE_ADDR} !^127\.127\.127\.127
RewriteCond %{REMOTE_ADDR} !^128\.128\.128\.128

RewriteCond %{HTTP_REFERER} !^http://www\.example\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://example\.com/ [NC]

RewriteRule ^.*$ http://www.example.com [R=301,L]
BT643
  • 3,495
  • 5
  • 34
  • 55
-3

I guess you should add [OR] modifier after each RewriteCond, like this:

RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123 [OR]
RewriteCond %{REMOTE_ADDR} !^124\.124\.124\.124 [OR]
...
John F
  • 685
  • 1
  • 8
  • 18