代理自动配置(PAC)如何编写

代理自动配置(PAC)文件是一组用JavaScript编码的脚本,用于确定web浏览器请求是直接发送到它们想要的目的地,还是被转发到web代理服务器。
换句话说,PAC文件定义了web浏览器/设备如何自动选择适当的访问方法(代理或直接)来获取给定的URL。

PAC文件的最大优点是,它们通常相对容易创建和维护,它们只允许您代理您想要代理的站点,将隐私考虑在内,并将快速处理最小化。

PAC的好处

  • 灵活和可扩展
  • 支持所有流行的浏览器
  • 易于管理和维护在任何规模的网络
  • 能够支持使用标准浏览器的移动设备

PAC文件包含基本结构:

function FindProxyForURL(url, host) {
// This is a template PAC file for schools built by Lightspeed Systems
// Your proxy server name and port
  var proxy_yes = "PROXY YOUR_PROXY_FQHN:PORT";
  var proxy_no = "DIRECT";
// If the hostname matches, send to proxy.
if (shExpMatch(url, "*.google.com/*"))
    return proxy_yes;
// DEFAULT RULE: All other traffic, send direct
    return proxy_no;
}

Function

function FindProxyForURL(url, host){
}  

当web浏览器发出请求时,请求首先通过PAC文件查看被请求的URL是否与函数中设置的任何规则相匹配。

参数
URL——web浏览器请求的URL。
Host——从URL中提取的主机名。

结果
当函数被执行时,它根据在函数本身中设置的规则来决定请求应该发生什么。

结果通常如下:
DIRECT – 没有任何代理
PROXY – 应该代理连接。

完整例子:

var domains = {
    "google.com": 1,
    "*.google.com": 1,
    "facebook.com": 1,
    "*.facebook.com":1
};

var proxy = "SOCKS5 192.168.0.75:8090; PROXY 192.168.0.75:8060;";

var direct = 'DIRECT;';

function FindProxyForURL(url, host) {
    var lastPos;
    do {
        if (domains.hasOwnProperty(host)) {
            return proxy;
        }
        lastPos = host.indexOf('.') + 1;
        host = host.slice(lastPos);
    } while (lastPos >= 1);
    return direct;
}

参考资料

https://developer.mozilla.org/en-US/docs/Web/HTTP/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_(PAC)_file

负载均衡算法有哪些
你应该知道JavaScript中的7种原生错误
ajax-loader