用node-http-proxy搭建谷歌代理

来源:互联网 发布:购票软件有哪些 编辑:程序博客网 时间:2024/06/05 11:34

程序员三大必备网站是:Google、Github、StackOverflow。如果你还在用Baidu搜索技术文章的话,我想说的是,少年你已经被鄙视很多年了,赶紧换成谷歌吧,不要再被鄙视了!Github、StackOverflow在国内能够正常访问,但是Google由于众所周知的原因,国内无法访问,所以我们需要翻墙访问Google。个人觉得shadowsocks的是目前最好用的代理,没有之一!shadowsocks有多牛?前段时间shadowsocks的作者被约谈了,还被要求删除在Github上的源码,你说有多牛!可以自己在vps上利用shadowsocks搭建自己的专属代理,如果你懒的话,也可以直接去买个shadowsocks账号,网上卖家多的是。后面我会写相关的文章介绍如何在vps上搭建服务器,敬请关注。今天先介绍一下用node-http-proxy搭建谷歌代理,小试牛刀一下。

node-http-proxy是一个用于Node.js的HTTP可编程代理库,支持 websockets。它是适用于实现例如代理服务器和负载均衡这样的组件。node-http-proxy使用起来很简单,下面简单介绍一下。

核心概念

通过createProxyServer函数创建代理,同时你也可选的传入options对象

var httpProxy = require('http-proxy');var proxy = httpProxy.createProxyServer(options);

createProxyServer函数返回的proxy对象包含四个方法

  • web req, res, [options] 用来代理http(s)请求
  • ws req, socket, head, [options] 用来代理WS(S)请求
  • listen port 该函数把对象包装成webserver,方便使用
  • close [callback] 该函数关闭内部的webserver并且停止监听给定的端口

然后可以如下调用函数代理请求

http.createServer(function(req, res) {  proxy.web(req, res, { target: 'http://mytarget.com:8080' });});

错误处理可以通过监听error事件

proxy.on('error', function(e) {  ...});

或者使用回调API

proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });

Use Cases

下面的例子显示如何用你自己的http服务器代理请求,你也可以加入自己的业务逻辑处理请求

var http = require('http'),    httpProxy = require('http-proxy');//// Create a proxy server with custom application logic//var proxy = httpProxy.createProxyServer({});//// Create your custom server and just call `proxy.web()` to proxy// a web request to the target passed in the options// also you can use `proxy.ws()` to proxy a websockets request//var server = http.createServer(function(req, res) {  // You can define here your custom logic to handle the request  // and then proxy the request.  proxy.web(req, res, { target: 'http://127.0.0.1:5060' });});console.log("listening on port 5050")server.listen(5050);

更多例子请查看官方文档

Options

httpProxy.createProxyServer支持下列options:

  • target: url字符串
  • forward: url字符串
  • agent: 传给http(s).request的对象
  • ssl: 密钥,HTTPS使用
  • ws: true/false, 是否代理websockets
  • xfwd: true/false, 是否加上x-forward头字段
  • secure: true/false, 是否校验ssl证书
  • toProxy: 传递绝对URL作为path
  • prependPath: true/false, 默认值为true,是否在proxy path前面加上target的path
  • ignorePath: true/false, 默认值为false,是否忽略传入的请求的proxy path
  • localAddress: 本地地址
  • changeOrigin: true/false, 默认值为false, 是否更改原始的host头字段为target URL
  • auth: 基本身份认证,比如:‘用户名:密码’来计算Authorization header
  • hostRewrite: 重写重定向(301/302/307/308)的location hostname
  • autoRewrite: 是否自动重写重定向(301/302/307/308)的location host/port,默认值为false
  • protocolRewrite: 重写重定向(301/302/307/308)的location的协议,http或者https,默认值为null

谷歌代理

'use strict';var http = require('http');var https = require('https');var httpProxy = require('http-proxy');var url = require('url');var PROXY_PORT = 8000;var proxy, server;// Create a proxy server with custom application logicproxy = httpProxy.createProxy({});proxy.on('error', function (err) {    console.log('ERROR');    console.log(err);});server = http.createServer(function (req, res) {    //var finalUrl = req.url,    var finalUrl = 'https://www.google.com';    var finalAgent = null;    var parsedUrl = url.parse(finalUrl);    if (parsedUrl.protocol === 'https:') {        finalAgent = https.globalAgent;    } else {        finalAgent = http.globalAgent;    }    proxy.web(req, res, {        target: finalUrl,        agent: finalAgent,        headers: { host: parsedUrl.hostname },        prependPath: false,        xfwd : true,        hostRewrite: finalUrl.host,        protocolRewrite: parsedUrl.protocol    });});console.log('listening on port ' + PROXY_PORT);server.listen(PROXY_PORT);

你没看错,就是这么点代码就能代理谷歌了,前提是你要有个墙外的vps哈!首先设置浏览器的http代理为你的vps,然后再vps上运行上面的代理程序,最后在浏览器中访问www.google.com,然后就是见证奇迹的时候了。有些小伙伴可能迫不及待的拿去试了试,结果发现博主骗人,根本不能代理谷歌。别急,这是因为node-http-proxy有一个小小的bug,不能怪博主,博主也是受害者之一。博主开始也卡在这里很久,最后去阅读源代码才发现问题所在!在node-http-proxy的web-outgoing.js里有个setRedirectHostRewrite函数,该函数的功能就是重定向时重写header中location的host地址,函数代码如下:

function setRedirectHostRewrite(req, res, proxyRes, options) {    if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite)        && proxyRes.headers['location']        && redirectRegex.test(proxyRes.statusCode)) {      var target = url.parse(options.target);      var u = url.parse(proxyRes.headers['location']);      // make sure the redirected host matches the target host before rewriting      if (target.host != u.host) {        return;      }      if (options.hostRewrite) {        u.host = options.hostRewrite;      } else if (options.autoRewrite) {        u.host = req.headers['host'];      }      if (options.protocolRewrite) {        u.protocol = options.protocolRewrite;      }      proxyRes.headers['location'] = u.format();    }  }

问题出在以下代码:

// make sure the redirected host matches the target host before rewriting     if (target.host != u.host) {        return;      }

作者的意图是确保重定向的host跟target的host的匹配,不匹配就直接返回。代理谷歌时就会发生不匹配的情况直接返回了。
比如,博主来自中国,当我curl www.google.com时会重定向到www.google.com.hk:

[root@iZu1fmzgm3iZ ~]# curl www.google.com<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"><TITLE>302 Moved</TITLE></HEAD><BODY><H1>302 Moved</H1>The document has moved<A HREF="http://www.google.com.hk/url?sa=p&amp;hl=zh-CN&amp;pref=hkredirect&amp;pval=yes&amp;q=http://www.google.com.hk/%3Fgws_rd%3Dcr&amp;ust=1448378903186576&amp;usg=AFQjCNHtMfRNndvgHHMAzipRzC9NpycwGw">here</A>.</BODY></HTML>

如果你来自日本,当你curl www.google.com时会重定向到www.google.co.jp:

[ec2-user@ip-172-31-27-165 ~]$ curl www.google.com<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"><TITLE>302 Moved</TITLE></HEAD><BODY><H1>302 Moved</H1>The document has moved<A HREF="http://www.google.co.jp/?gfe_rd=cr&amp;ei=toJUVubpIcem8wfGirqQDw">here</A>.</BODY></HTML>

因为重定向的host跟target的host不匹配,程序直接返回,hostRewrite无效,所以我们应该去掉以下代码:

// make sure the redirected host matches the target host before rewriting     if (target.host != u.host) {        return;      }

当我们注释掉以上代码,重新运行程序,发现已经可以上谷歌了,是不是很神奇!

本文链接:http://blog.noobsky.com/2015/11/24/用node-http-proxy搭建谷歌代理/

– EOF –

0 0
原创粉丝点击