过滤IP区段的好用的apache 模块(module)mod-ipenv

原来的有点错,因为module对request的处理顺序,mod-ipenv生成的变量不能被Rewrite使用。
要改源码:

//static const char* const post_modules[] = { "mod_setenvif.c", NULL };
static const char* const post_modules[] = { "mod_setenvif.c", "mod_rewrite.c", NULL };
static const char* const aszPost[] = { "mod_rewrite.c", NULL };

static void ipenv_register_hooks(apr_pool_t* p){
//ap_hook_header_parser(ipenv_process, NULL, post_modules, APR_HOOK_MIDDLE);
/*This seems the best hook point to make ipenv useful.*/
ap_hook_post_read_request(ipenv_process, NULL, post_modules, APR_HOOK_MIDDLE);
}
确保 mod_ipenv 在mod_rewrite前被执行。


要架设两台服务器,从日本到中国服务器的访问,重定向到日本服务器。
从中国到日本服务器的访问,重定向到中国服务器。

因为有静态内容,所以不适合在脚本程序中重定向。
只好想办法使用apache的url rewrite。
找到了国家的ip区段,开始写RewriteCond规则
发现,mod_rewrite支持的RewriteCond虽然支持使用${REMOTE_ADDR}取得客户端IP地址,但是,拿到的只有字符串形式的ip地址,也只支持正则表达式的判断。

想办法用脚本生成正则表达式规则,结果自己都不满意。后来想到,apache有个自带module, SetEnv,可以设置环境变量。这就意味着可以自己写个模块,把ip转成好比较范围的形式。

找module的编写文档,结果进到apache网站的一个module查询页面,
http://modules.apache.org/
抱着试试看的想法,查找有没有人做了类似的事,结果找了 mod-ipenv: http://mod-ipenv.sourceforge.net/

加载指令
  LoadModule ipenv_module  mod_ipenv.so
(还需要加载mod_setenvif, SetEnvIf 设置的值才能被 mod_rewrite获取)
加载后,可以使用指令 SetEnvIp 来根据ip规则声明,或者取消声明(用!)一个变量
SetEnvIp access/cn.conf IP_FROM_CHINA
   当客户端地址满足cn.conf里的条件时(单个IP,区段,域名),IP_FROM_CHINA将被设置。
   这下简单了,按照mod-ipenv的规则设置cn.conf文件之后
SetEnvIf IP_FROM_CHINA 1+ FROM_CHINA=yes
RewriteCond ${FROM_CHINA} ^yes$
RewriteRule ^/(.*)$ http://www.xxxx.com.cn/$1 [R=302,L]

Rewrite相关的指令 可以放到.htaccess里

猜你喜欢

转载自dwangel.iteye.com/blog/638928