PAC 文件

通过代理自动配置(PAC:proxy auto config)文件,实现自动在多个代理、直联之间连接。

前提:您已经知道如何在OS或浏览器上,配置代理网络的方法,以及您已经有代理服务器了。

代理自动配置(PAC:proxy auto config)文件是一个 JavaScript 脚本,其核心是一个 JavaScript 函数,用来决定网页浏览请求(HTTP、HTTPS,和 FTP)应当直连目标地址,还是被转发给一个代理服务器并通过代理连接。

mozilla 文档上写的很复杂,实际中更多只需要通过域名来判断就可以了,这样就简单了,看下面的示例:

  • 列出来域名,通过 SOCKS5 127.0.0.1:1080 代理;其他则 DIRECT 直联。
function FindProxyForURL(url, host) {
    if ( dnsDomainIs(host,"google.com") || dnsDomainIs(host,"gstatic.com") || dnsDomainIs(host,"googleapis.com") || dnsDomainIs(host,"googleusercontent.com")
      || dnsDomainIs(host,"github.com") || dnsDomainIs(host,"githubusercontent.com")
      || dnsDomainIs(host,"x.com") || dnsDomainIs(host,"twitter.com") || dnsDomainIs(host,"twimg.com")
      || dnsDomainIs(host,"facebook.com") || dnsDomainIs(host,"fbcdn.net")
      || dnsDomainIs(host,"wikipedia.com") || dnsDomainIs(host,"wikipedia.org")
      || dnsDomainIs(host,"steamcommunity.com")
    ) {
      return "SOCKS5 127.0.0.1:1080";
    }
    return "DIRECT"; 
} 

/* 
如果OS或浏览器,不支持pac里有注释,请删除此区域内容。
代理自动配置(PAC)文件:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_PAC_file
JavaScript 教程:https://www.runoob.com/js/js-tutorial.html

1、js 逻辑运算符
示例 x=6 以及 y=3
&& 为and,(x < 10 && y > 1) 为 true
|| 为or,(x==5 || y==5) 为 false
!  为not,!(x==y) 为 true

2、js if语句,else子句是可选,if是可以嵌套。
if (条件)
{
    当条件为 true 时执行的代码
}
else
{
    当条件不为 true 时执行的代码
}

3、js return 退出函数
执行结束,不再向执行后面的代码。

10、function FindProxyForURL(url, host) {}
示例 https://developer.mozilla.org:80/zh-CN/
url为developer.mozilla.org:80/zh-CN/。
host为developer.mozilla.org,为url中主机名,不包含端口号。

11、dnsDomainIs(host, domain)
domain在host中匹配成功,返回 true。
dnsDomainIs("www.mozilla.org", ".mozilla.org"); // true,因为【www.mozilla.org"】中匹配到了【.mozilla.org】
dnsDomainIs("www", ".mozilla.org"); // false

12、代理配置
直连            DIRECT
http 代理    PROXY host:port
SOCKS 代理    SOCKS[4|5] host:port
多个代理,如果PROXY主代理出现问题,则使用SOCKS代理连接:
            PROXY w3proxy.netscape.com:8080; SOCKS socks:1080

如果 return "xxx"; 语句多或代理服务器多,可以使用变量。
在 function FindProxyForURL(url, host) {} 的{}中第一行,定义代理服务器,比如:
var proxy1 = "PROXY host:port"
则在 return proxy1;

20、shExpMatch(str, shexp)  //firefox无效果
str为任何要比较的字符串,shexp 要用来对比的 Shell glob表达式,而非正则表达式。
示例1:shExpMatch(host,"x.com")
host为www.x.com或x.com,返回 true
host为z.cn,返回 false
示例2:shExpMatch(host,"img.x.com")
host为www.x.com或x.com,返回 false
*/

如果是需要在自己的WEB Server上,提供pac文件服务,就需要在WEB Server配置以对应的 MIME 类型记录:

application/x-ns-proxy-autoconfig pac;

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注