0

当用户访问如下所示的 URL 时,我正在尝试让 nodejs 网站/服务器下载另一个网站:http://example.com/test/http://google.com

问题是 nginx 正在将 req.url 重写为/test/http:/google.com应该的时间/test/http://google.com

应用程序.js:

var express = require('express');
var http = require('http');
var app = express();

app.configure(function(){
    app.set('port', 8080);
    app.set('views', __dirname + '/app/server/views');
    app.set('view engine', 'jade');
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({ secret: 'super-duper-secret-secret' }));
    app.use(express.methodOverride());
    app.use(require('stylus').middleware({ src: __dirname + '/app/public' }));
    app.use(express.static(__dirname + '/app/public'));

    app.enable('trust proxy')

});

app.configure('development', function(){
    app.use(express.errorHandler());
});

require('./app/server/router')(app);

http.createServer(app).listen(app.get('port'), 'localhost', function(){
    console.log("Express server listening on port " + app.get('port'));
})

路由器.js:

app.get('/test/*', function(req, res) {
    console.log("REQ.URL:");
    console.log(req.url);
    res.send('200', req.url);
});

example.com 文件在/etc/nginx/sites-enabled

server {
        server_name example.com;
        access_log /var/log/nginx/example.com.log;
        # pass the request to the node.js server with the correct headers and much more can be added, see nginx config options
        location / {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_set_header X-NginX-Proxy true;
                proxy_pass http://127.0.0.1:8080;
                proxy_redirect off;
        }
}

有没有办法让 nginx 不像它那样重写?

4

3 回答 3

2

也许像这样的东西(未经测试的代码)是你所追求的:

app.get('/test/:url', function(req, res) {
    console.log("req.params.url:", req.params.url);
    res.send('200', req.params.url);
});
于 2013-09-24T15:05:46.597 回答
0

这段代码解决了这个问题。

if(req.url.match(/https?:\/[^\/]/)) {
    req.url = req.url.replace(/(https?\:)\/([^\/])/, "$1//$2");
}

所以最终的代码看起来像这样

app.get('/test/*', function(req, res) {
    console.log("REQ.URL:");
    console.log(req.url);
    if(req.url.match(/https?:\/[^\/]/)) {
        req.url = req.url.replace(/(https?\:)\/([^\/])/, "$1//$2");
    }
    console.log("REQ.URL FIXED:");
    console.log(req.url);
    res.send('200', req.url);
});

如果有人知道如何在 Express 中修复它以便它不会重写路径,我会将您的答案标记为正确答案。

于 2013-09-25T08:50:19.170 回答
0

尝试使用req.originalUrl.

app.get('/test/*', function(req, res) {
    console.log(req.originalUrl);
    res.send('200', req.originalUrl);
});
于 2013-09-25T15:09:20.167 回答