[英]nginx rewrites paths proxied to node.js
當用戶訪問如下所示的URL時,我正在嘗試讓nodejs網站/服務器下載另一個網站: http://example.com/test/http://google.com
: http://example.com/test/http://google.com
: http://example.com/test/http://google.com
問題是nginx會將/test/http:/google.com
重寫為/test/http:/google.com,應該是/test/http://google.com
app.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'));
})
router.js:
app.get('/test/*', function(req, res) {
console.log("REQ.URL:");
console.log(req.url);
res.send('200', req.url);
});
/etc/nginx/sites-enabled
example.com文件
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不像它那樣重寫?
也許這樣的事情(未經測試的代碼)就是你所追求的:
app.get('/test/:url', function(req, res) {
console.log("req.params.url:", req.params.url);
res.send('200', req.params.url);
});
此代碼修復了此問題。
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中修復它,以便它不會重寫路徑,我會將你的答案標記為正確的答案。
嘗試使用req.originalUrl
。
app.get('/test/*', function(req, res) {
console.log(req.originalUrl);
res.send('200', req.originalUrl);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.