Andrew G. Johnson
Andrew G. Johnson

Reputation: 26993

How can I write an htaccess rewriterule to exclude an IP range?

So I just implemented AWS' CloudFront and I need to exempt their IP ranges from a few htaccess rules. Here is a link to their ranges: https://forums.aws.amazon.com/ann.jspa?annID=910

Here is an example of an htaccess rule I don't want them to use:

# ROUTE CLOUDFRONT DOMAINS
rewritecond %{HTTP_HOST} ^www1.
rewriterule ^ http://www.domain.com%{REQUEST_URI} [L,R=301]

How can I write another rewritecond [or multiple] to ignore the 204.246.160.0/19 range?

Upvotes: 2

Views: 7538

Answers (2)

TerryE
TerryE

Reputation: 10888

If my math is correct then 204.246.160.0/19 is 204.246.160.* thru 204.246.191.* so the regexp to match this is 204\.246\.1([678]\d|19[01]\.\d+ and therefore the cond is

RewriteCond %{REMOTE_ADDR} !204\.246\.1([678]\d|19[01])\.\d+

Adddendum

You've got some non-significant errors in your regexps like [0,9] when you mean [09] and "." instead of ".". But you can assume that the IP address will be valid so you can simplify these and this was the simplest that I came up with:

#Filter the 204.246.160.0/19 and 216.137.32.0/19 IP subranges
RewriteCond %{REMOTE_ADDR} !^(204\.246\.1([678]\d|19[01])|216\.137\.(3[2-9]|[45]\d|6[0-3]))\.
#Filter the 205.251.xxx and 207.171.xxx /2[34] IP subranges
RewriteCond %{REMOTE_ADDR} !^(205\.251\.2(0[24567]|1[01489]|20|22|49|50|52)\|207\.172\.17[09])\.

However my real concern if the statement on your referenced announcement "The CloudFront IP addresses change frequently and we cannot guarantee advance notice of changes ... Customers should not use these addresses for mission critical applications and must never hard code them in DNS names."

Is there no better way of intercepting these CloudFront IPs -- e.g. from the request headers?

Upvotes: 2

anubhava
anubhava

Reputation: 785146

You can block (or allow) range of IP addresses like this:

# block a range of IPs
RewriteCond %{REMOTE_ADDR} =204\.246\.160\.([0-9]|1[0-9])
RewriteRule ^ - [F,L]

Specifically for your existing rule you can use:

# if domain name has www1 at start
RewriteCond %{HTTP_HOST} ^www1\. [NC]
# but request not coming from 204.246.160.0/19 IP range
RewriteCond %{REMOTE_ADDR} !=204\.246\.160\.([0-9]|1[0-9])
# redirect to http://www.domain.com/uri
RewriteRule ^ http://www.domain.com%{REQUEST_URI} [L,R=301]

Upvotes: 2

Related Questions