[原]apache模块的编写实例 (反向透明代理实现方式之一)
Posted by bianbian on 2006-10-30 07:45
除了用端口映射(当然,要在转发数据包前传递客户端IP地址给内网服务器)来实现反向透明代理以外,利用apache的mod_proxy也是一种办法。而后一种办法更方便的地方是一个80端口可以给很多域名使用(即虚拟主机)——当然前一种也是可以,只要根据不同域名把数据包转发到不同内网服务器而已,我只是懒得写而已;因为工作量显然是直接用apache来得少。。。。
我贴出用后一种办法实现以前lilybbs.net公网代理的代码;之所以要自己写apache的模块,是因为直接用mod_proxy是不能传递客户端的IP地址给真正的内网服务器的。我原本打算是插入自定义的一个HTTP头来实现IP传递,这样一般是没有问题;但是当客户端本身访问网络经过Squid代理时,Squid会删除掉非标准的HTTP头,真是FT。所以我采用的方法是通过”Accept-Language”头传递客户端IP地址,”Accept-Language”是用来标示客户端接受的页面语言顺序(中文?英文?之类),在非国际化的网站中并没有很大的用处。
apache的模块编写其实很简单,大部分都是架子工程,直接贴过来就可以。
代码如下(代码经过lilybbs.net公网访问测试OK,不过现在学校网络中心停止了lilybbs.net的公网出口)。
- /*
- apache 2.x 模块
- 所有http请求的header发送ip,以实现代理
- 如需使用 LilybbsipEnable 设为 on 即可(需要和mod_proxy一起使用)
- 编译:
- /home/apache2/bin/apxs -i -a -c mod_lilybbsip.c
- 参考:
- http://modules.apache.org/
- 作者:
- Net@Lilybbs, 2006-3-26 17:38
- http://bianbian.org
- */
- #include "httpd.h"
- #include "http_config.h"
- #include "http_core.h"
- #include "http_log.h"
- #include "http_protocol.h"
- #include "http_vhost.h"
- #include "apr_strings.h"
- module AP_MODULE_DECLARE_DATA lilybbsip_module;
- typedef struct {
- int enable;
- } lilybbsip_server_cfg;
- static void *lilybbsip_create_server_cfg(apr_pool_t *p, server_rec *s) {
- lilybbsip_server_cfg *cfg = (lilybbsip_server_cfg *)apr_pcalloc(p, sizeof(lilybbsip_server_cfg));
- if (!cfg)
- return NULL;
- cfg->enable = 0;
- return (void *)cfg;
- }
- static const char *lilybbsip_enable(cmd_parms *cmd, void *dummy, int flag) {
- lilybbsip_server_cfg *cfg = (lilybbsip_server_cfg *)ap_get_module_config(cmd->server->module_config, &lilybbsip_module);
- cfg->enable = flag;
- return NULL;
- }
- static const command_rec lilybbsip_cmds[] =
- {
- AP_INIT_FLAG(
- "LilybbsipEnable",
- lilybbsip_enable,
- NULL,
- RSRC_CONF,
- "Enable mod_lilybbsip"
- ),
- { NULL }
- };
- static int ip_lilybbsing_handler(request_rec *r) {
- lilybbsip_server_cfg *cfg = (lilybbsip_server_cfg *)ap_get_module_config(r->server->module_config, &lilybbsip_module);
- if (!cfg->enable)
- return DECLINED;
- //通过Accept-Language传递IP
- apr_table_set(r->headers_in, "Accept-Language", r->connection->remote_ip);
- return DECLINED;
- }
- static void register_hooks(apr_pool_t *p)
- {
- ap_hook_post_read_request(ip_lilybbsing_handler, NULL, NULL, APR_HOOK_MIDDLE);
- }
- module AP_MODULE_DECLARE_DATA lilybbsip_module =
- {
- STANDARD20_MODULE_STUFF,
- NULL,
- NULL,
- lilybbsip_create_server_cfg,
- NULL,
- lilybbsip_cmds,
- register_hooks,
- };
使用的时候在vhost(虚拟主机)内设定:
LilybbsipEnable On
ProxyRequests Off
ProxyPass / http://bbs.nju.edu.cn
遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道
October 31st, 2006 at 11:39:32
haproxy, 可以实现同样的功能,可以参考一下,very的不错
November 4th, 2006 at 10:36:02
朋友,您好,我喜欢AUTOIT,请问可以加我吗,谢谢。我的msn:dowson1982@hotmail.com