Nginx代理转发

目录

  • Server

    • Server1

    • Server2

  • nginx

  • Test

Server

cnpm i -g express-generator pm2

Server1

express Server1
# cd Server1
cnpm i

sed -i 's/3000/5001/g' ./bin/www

tee ./routes/index.js <<-'EOF'
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send(JSON.stringify({ msg: 'Server1' }));
});

module.exports = router;
EOF

MacOS下sed修改文件明了和Ubuntu不同: sed -i "" 's/3000/5001/g' ./bin/www

pm2 start bin/www

Server2

express Server2
# cd Server2
cnpm i

sed -i 's/3000/5002/g' ./bin/www

tee ./routes/index.js <<-'EOF'
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send(JSON.stringify({ msg: 'Server2' }));
});

module.exports = router;
EOF

MacOS下sed修改文件明了和Ubuntu不同: sed -i "" 's/3000/5002/g' ./bin/www

pm2 start bin/www

nginx

sudo vim /etc/nginx/conf.d/proxy.conf
server {
    listen 80;
    server_name test.com;

    location / {
        proxy_pass http://localhost:5001;
        if ($http_ZeahoRelease = "1.7.0") {
            proxy_pass http://localhost:5002;
        }

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
sudo nginx -t

sudo nginx -s reload
# hosts
sudo sh -c "echo '47.75.67.227 test.com' >> /etc/hosts"

Test

curl test.com # 返回"Server1"

curl --header "ZeahoRelease:1.7.0" test.com # 返回"Server2"

参考

  • nginx if header not set

你可能感兴趣的:(Nginx代理转发)