簡體   English   中英

NodeJS-具有路由更改的反向代理

[英]NodeJS - Reverse Proxy with Route Changing

我目前正在使用NodeJS / Express作為運行在端口80上的VPS上的簡單域路由器。我的route.coffee看起來像這樣:

request = require("request")

module.exports = (app) ->

    #404, 503, error
    app.get "/404", (req, res, next) ->
        res.send "404. Sowway. :("

    app.get "/error", (req, res, next) ->
        res.send "STOP SENDING ERRORS! It ain't cool, yo."

    #Domain Redirects
    app.all '/*', (req, res, next) ->
        hostname = req.headers.host.split(":")[0]

        #Website1.com
        if hostname == 'website1.com'
            res.status 301
            res.redirect 'http://facebook.com/website1'

        #Example2.com
        else if hostname == 'example2.com'
            pathToGo = (req.url).replace('www.','').replace('http://example2.com','')
            request('http://localhost:8020'+pathToGo).pipe(res)

        #Other
        else
            res.redirect '/404'

如您在Example2.com中所看到的,我正在嘗試將代理反向代理到另一個端口上的另一個節點實例。 總體來說,它很完美,除了一個問題。 如果其他節點實例上的路由發生更改(從example2.com/page1.html重定向到example2.com/post5) ,則地址欄中的URL不變。 有人會碰巧有一個很好的解決方法嗎? 還是反向代理的更好方法? 謝謝!

為了重定向客戶端,您應該將3xx並發送位置標頭。

我對請求模塊不熟悉,但我相信默認情況下它遵循重定向。 另一方面,您正在將代理請求的響應傳遞到客戶端的響應對象,而丟棄頭和狀態代碼。 這就是為什么客戶端不會被重定向。

這是一個使用內置HTTP客戶端的簡單反向HTTP代理。 它是用編寫的,但是您可以輕松地將其翻譯為並使用請求模塊。

var http = require('http');
var url = require('url');

var server = http.createServer(function (req, res) {
  parsedUrl = url.parse(req.url);

  var headersCopy = {};
  // create a copy of request headers
  for (attr in req.headers) {
    if (!req.headers.hasOwnProperty(attr)) continue;
    headersCopy[attr] = req.headers[attr];
  }

  // set request host header
  if (headersCopy.host) headersCopy.host = 'localhost:8020';

  var options = {
    host: 'localhost:8020',
    method: req.method,
    path: parsedUrl.path,
    headers: headersCopy
  };

  var clientRequest = http.request(options);

  clientRequest.on('response', function (clientResponse) {
    res.statusCode = clientResponse.statusCode;
    for (header in clientResponse.headers) {
      if (!clientResponse.headers.hasOwnProperty(header)) continue;
      res.setHeader(header, clientResponse.headers[header]);
    }
    clientResponse.pipe(res);
  });

  req.pipe(clientRequest);
});

server.listen(80);

// drop root privileges
server.on('listening', function () {
  process.setgid && process.setgid('nobody');
  process.setuid && process.setuid('nobody');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM