Tuesday, 30 April 2019

redirection - How do regular expressions work in htaccess to redirect an IP range


I've been trying to redirect an IP range from one link to another. I can do it for a single 256 address block:


RewriteEngine On
RewriteBase /
RewriteCond %{REMOTE_HOST} ^111\.111\.111\.
RewriteCond %{REQUEST_URI} /original_link/$
RewriteRule .* /new_link/ [R=301,L]

However, trying to block a 8192 address range (xxx.xxx.128.0 - xxx.xxx.159.255) requires regular expressions to express the redirect properly. Even though I found some examples, I couldn't make much sense of the values that have to be put in brackets. Can somebody please explain how to use those expressions properly?


My own attempt would look something like this:


RewriteCond %{REMOTE_HOST} ^xxx\.xxx\.1([2-5][8-9])

Answer



No, that would only match


xxx.xxx.128
xxx.xxx.129
xxx.xxx.138
xxx.xxx.139
xxx.xxx.148
xxx.xxx.149
xxx.xxx.158
xxx.xxx.159

What you want (if regexes is even the right tool; I'm not sure if there is a better way to match on netmasks that works here) would be


^xxx\.xxx\.1(2[89]|[3-5][0-9])

The parenthesised part matches either 2 followed by 8 or 9, or 3, 4, or 5 followed by any digit.


You need the "any digit" in the second case, because otherwise the regex would match, for example, xxx.xxx.13.57 which is not in your range.


No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...