Simple node.js reverse proxy to Google sites service

沈溺在Google服務的玩家,對Google Sites服務應該不陌生
但是最近Google的Sites DNS轉址服務暫停了...
是否意味著這個進階服務會開始收費了呢??
不得而知拉...
不過如果可以透過簡單的設定把Sites服務轉到自己的Domain下的話....

這邊介紹"幾行"Node.js程式,可以把sites的所有網頁都轉到你要的網址上...
透過/ request 的pipe request/response的功能
可以輕易地把sites的網頁都經由寫好的這隻程式來轉址噢...
PS: 安裝就.... npm install request

# vi test-request.js
  1 var http = require('http')
  2   , request = require('request');
  3 
  4 //google site url
  6 //google site domain (change to yours)
  7 url += 'simonsumail';
  8 
  9 http.createServer(function (req, resp) {
 10   console.log(req.url);
 11   if (req.method === 'PUT') {
 12     req.pipe(request.put(url + req.url))
 13   } else if (req.method === 'GET' || req.method === 'HEAD') {
 14     request.get(url + req.url).pipe(resp);
 15   }
 16 }).listen(80, '211.78.255.92'); //ipaddress that the node server host

# node test-request.js

接下來就看一下原站跟轉址過的站�吧!






這只是個簡單的http request redirect的範例,或許會有一些特殊的程式碼因為hard code了整個絕對路徑網址而會造成路徑的不一致現象
要解決這個問題,可以在取得頁面資訊時候,統一將URL路徑做個置換
這邊就不能用pipe了,因為pipe會限制不能針對response的資料作修改
而改用server read to write response的方式...
而不用修改內容的網頁或資源項目,就通通給他直接pipe過去...
笨笨的做法,不過...將就用拉~ :P

  1 var request = require('request')
  2   , http = require('http')
  3   , server = '211.78.255.92'
  4   , port = 80
  6 
  7 http.createServer(function (req, res) {
  8   var isWait = true;
  9 
 10   if(isNoParse(req.url)) {
 11     request.get(url + '/' + req.url).pipe(res);
 12   } else {
 13     var opts = {
 14       "uri": url + '/' + req.url
 15     }
 16     var r = request(opts, function (error, response, body) {
 17       if (!error && response.statusCode == 200) {
 18         response.body = response.body.replace(/https:\/\/sites.google.com/g,'');
 19         response.body = response.body.replace(/\/site\/simonsumail/g,'');
 20         doit(response);
 21       }
 22     })
 23     function doit(response){
 24      res.writeHead(200, r.response.headers);
 25      res.end(response.body);
 26     }
 27   }
 28 }).listen(port, server);
 29 
 30 /* contents that no need to replace the content */                                                                                                                                                  
 31 function isNoParse(url) {
 32   console.log(url); 
 33   var pic = ['jpg', 'png', 'gif'];
 34   for(var i=0; i< pic.length; i++ ) { //pic.forEach(function(u) {
 35     if(url.indexOf(pic[i])>0) {
 36       return true;
 37     }
 38   }
 39   return false;
 40 }

最完整的做法還是透過較強的reverse proxy,像是Http Proxy或是load balancer來作完整的資料導向
一般這樣的軟體都還有提供response rewrite的功能喔~

這個網誌中的熱門文章

Bash判斷參數是否存在

Node.js package : forever