Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htaccess command to only allow requests from same server (without specifying the IP)

What I'm trying to achieve is to use htaccess to only allow requests coming in from the same server, but do so by using available variables and not specify the IP. The goal is to be able to run cron jobs and ajax requests to the files in the respective folder, but return a 404 page if tried to access directly.

Here's what I have so far:

Options -MultiViews +FollowSymLinks  
RewriteEngine On    
RewriteCond %{REMOTE_ADDR} !%{SERVER_ADDR}[NC]  
RewriteRule ^(.*)$ /error404.html [L,R=404]  

This works fine for ajax. It works for cronjobs too if the server happens to use the same outgoing IP, but if the server's outgoing IP is different from the IP of the site, obviously it will fail and return 404 because %{REMOTE_ADDR} is different from %{SERVER_ADDR}. One solution would be to see what the outgoing IP is for that server and add it as another exception. However I'm looking for a more reusable solution. I tried using regex to match only the first part of the IP's but I'm having no luck with that. Don't really know how to go about this. Basically with regex what I'm trying to achieve is this: let's assume:

%{REMOTE_ADDR} = 192.322.122.50  
%{SERVER_ADDR} = 192.322.122.1  

These are the 2 variables I need to find a valid comparison expression for. This expression would return true if the first part of the IP's is identical.

Another way would be to specify the range that is allowed, but I don't "know" what the wanted range is. I know it's the first part if the SERVER_ADDR variable, but I don't know how to tell the server what I mean :D

Hopefully I wasn't too confusing. Ultimately what I'm looking for is a way to determine whether a request is coming from the same server as the site this is on. And it has to be achieved through the .htaccess file. Why? Because the protected folder also contains files other than php scripts, so the alternative would be to serve all of those dynamically and use PHP for all the conditions. Using a plain htaccess command would be much more elegant. I just hope there is a way to do this.

like image 787
Owbey Avatar asked Nov 22 '11 21:11

Owbey


1 Answers

This isn't tested, but you may give it a try if you want:

# note that this only works if both server and visitor are using IPv4 addresses
RewriteCond %{SERVER_ADDR} ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$
RewriteCond %{REMOTE_ADDR} !^%1\.%2\.%3\.([0-9]{1,3})$
RewriteRule ^.*$ error404.html [R=404,L]

Let me know if this kind of stuff works, but don't shoot me if it doesn't :)

like image 194
Tom Knapen Avatar answered Nov 08 '22 17:11

Tom Knapen