Skip to content
Advertisement

Redirect ranges of IPs in JavaScript (no .htaccess)

I’m trying to redirect anyone viewing my blog from certain IP addresses (or ranges of IP addresses) to a different page. I found something that works for individual IP addresses, but I can’t figure out how to block ranges of IP addresses – like 123.123.123.*
Here’s the script:

<!-- check incoming IP address -->
<script type = "text/javascript" src="http://l2.io/ip.js?var=ip"></script>

<!-- redirect list -->
<script type = "text/javascript">
        window.onload = init();
        function init() {
            var blocklist = ["10.20.30.40","50.60.70.80"];
            for (var i = 0; i < blocklist.length; i++) {
                if (blocklist[i] == ip) {
                    window.location.replace('http://fakeblog.com/');
                    break;
                }
            }
        }
</script>

I’ve found some good advice for modifying .htaccess but I don’t have access to that file. Thanks!

Advertisement

Answer

Use a regular expression instead of an array:

var blocklist = /^(10.20.30.40|50.60.70.80|123.123.123..*)$/;
if (ip.match(blocklist)) {
    window.location.replace('http://fakeblock.com/');
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement