Allowing access to a URL for specific IPs
Here is the set of apache mod_rewrite rules for setting access to a specific URL to only a few IPs. In th is situation it is accomplished by using the following negative, or reverse, logic:
If the request is not from IP 1, or 2, or x
Send requests for the protected URL (protected.url) to the redirect or failure URL (redirect.url)
# Rules to ALLOW access to a specific URL
# The allowed IP addresses (listed as nots) can be as many as you need, one after the other
RewriteCond %{REMOTE_ADDR} !^xxx\.xxx\.xxx\.xxx
RewriteCond %{REMOTE_ADDR} !^yyy\.yyy\.yyy\.yyy
# Anyone else should be blocked
RewriteRule ^protected.url$ /redirect.url [R=301]
Some notes about the above rules.
- mod_rewrite needs to be on. This is done in my setup in the conf.modules.d/00-base.conf
LoadModule rewrite_module modules/mod_rewrite.so - The rewrite engine needs to be turned on in httpd.conf, or the site specific .conf file
RewriteEngine on - Because this is designed to allow certain IPs and redirect all others to a different URL, it uses NOT logic in defining the list of IPs. This is accomplished with the "!" symbol before the IP address in each RewriteCond statement.
- The "^" symbol marks the beginning of the string. This is important to allow 56.xx.xx.xx, but not 156.xx.xx.xx.
- The IP address needs to have the "." in it escaped, which is done using the backslash "\".
192.168.100.20 becomes 192\.168\.100\.20 - List as many addresses as needed by adding RewriteCond statements.
- To allow a whole class C network, just drop the last octet. ^192\.168\.100\. Include the trailing "\." to ensure the correct third octet (for example, if the class C was 192.168.10.xx, don't leave it as ^192\.168\.10, since this would match 10, 100, 101, 102, etc.
- To simply deny access with a 403 error rather than send the visitor to a different URL, the final rule would be
RewriteRule ^protected.url$ - [F]
More info can be found in the apache mod_rewrite documentation, here.