如何用Squid来实现Ajax跨域代理

什么是Ajax跨域代理?

玩Ajax的应该知道我在说什么:) 简单说就是因为浏览器的安全限制,你不能直接获取你站点以外的xml文档。

为什么用Squid来做?

你完全可以自己写一个代理小程序,比如用php,这方面的资料网上很多。
Squid是一个应用非常广泛、功能强大的代理服务器软件,用它自然是为了获得高效。

需要哪些软件?

Lighttpd(Apache)、Squid、squirm。 我这里以lighttpd为例,你完全可以用apache来代替。
这里介绍一下squirm,这是一款为squid量身定做的redirector程序,支持 正规表达式 ,至于什么是redirector下面的工作原理你会知道它的作用。
系统平台:理论上支持上述软件的应该都可以(比如选择常见的linux),我这里以freebsd为例。

工作原理

用Lighttpd(Apache)的proxy模块作前端代理,把特定url的请求发送到squid,比如把 /service/proxy/*/http://othersite.com/abc.xml 这样的请求发送给squid来处理。

squid通过squirm这个redirector对url进行修正(相当于url rewrite),通过squirm的配置文件我们可以把上述url地址重定向为 http://othersite.com/abc.xml ,这个过程对浏览器是透明的完全由squid完成。squid获取 http://othersite.com/abc.xml 后返回给浏览器,这样我们就实现了跨域,在Ajax应用中你如果要获取其他站点的内容就在url前加上 /service/proxy/*/ 即可。

关键配置

相关软件的基本配置网上很容易找到参考,我就不罗嗦了,下面给出关键的配置。

Lighttpd - lighttpd.conf,比如我们的squid将工作在6666端口,就作如下配置

$HTTP["url"] =~ "^/service/proxy/" {
    proxy.server = (
        "" => (
                   (
                        "host" => "127.0.0.1",
                        "port" => 6666
                    )
                )
    )
}

Squid - squid.conf

http_port 6666
redirect_program /usr/local/bin/squirm
redirect_children 5
redirect_rewrites_host_header on
httpd_accel_host virtual
httpd_accel_with_proxy on
httpd_accel_uses_host_header on

squirm
- squirm.conf 主要指定redirector的匹配规则文件的位置

begin
network 0.0.0.0/0
log /var/squid/logs/squirm-private-match.log
abort-log /var/squid/logs/squirm-private-abort.log
pattern common.patterns all
end

- common.patterns 这里的匹配规则文件是 common.patterns

regex ^.*/service/proxy/\*/(.*)$        \1

...
ok,that's all.

相关链接:
Squid: http://www.squid-cache.org
Lighttpd: http://www.lighttpd.net
Apache: http://www.apache.org
Squirm: http://squirm.foote.com.au

注:原文曾发布在http://www.mipang.com/groups/tiandi/t.331.d13577b5f3.htm

发表看法

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word