重定向JavaScript中的IP范围(无.htaccess)

时间:2015-06-05 00:11:19

标签: javascript redirect ip

ANSWERED - 如何在重定向中指定一系列IP地址

2 个答案:

答案 0 :(得分:0)

使用正则表达式而不是数组:

var blocklist = /^(10\.20\.30\.40|50\.60\.70\.80|123\.123\.123\..*)$/;
if (ip.match(blocklist)) {
    window.location.replace('http://fakeblock.com/');
}

答案 1 :(得分:0)

我会编写一个匹配IP的函数,它接受通配符。

/**
* Matches two ip's, supports the use of "wildcard", ex 192.168.*.*
*
* If an array of IP addresses is passed as the second argument, this
* function will return if any of them match.
*
* @param string A decimal separated IPv4 address
* @param string/[string] A, or an array of, decimal separated IPv4 addresses to match the first IP address against.
*/
function matchIP(ip, ipMatch) {
    if (ipMatch instanceof Array) {
        for (singleIpMatch in ipMatch) {
            if (matchIP(ip, singleIpMatch)) return true;
        }
        return false;
    }

    ipMatchParts = ipMatch.split('.');
    ipParts = ip.split('.');

    // IP is invalidly formatted 
    if (ipParts.length !== 4) {
        return false;
    }
    // IP match is invalidly formatted
    if (ipMatchParts.length !== 4) {
        return false;
    }

    matched = true;
    for (var i = 0; i < 4; i++) {
        if (ipParts[i] === '*') continue;
        if (ipMatchParts[i] === '*') continue;
        if (ipParts[i] === ipMatchParts[i]) continue;
        matched = false;
        break;
    }
    return matched
}

代码经过测试并且可以工作,插入到您的示例中,它看起来像:

<!-- 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.*.*.*","11.87.70.*"]; // For example
            for (var i = 0; i < blocklist.length; i++) {
                if (matchIP(ip, blocklist[i])) {
                    window.location.replace('http://fakeblog.com/');
                    break;
                }
            }
        }
</script>

NB!

如果重定向是出于安全原因,则不应在客户端进行。例如,客户端可能根本不运行JavaScript,请记住在客户端发生的所有事情都是一种选择,所以永远不要在客户端端安全。