当前位置: 移动技术网 > 网络运营>服务器>nginx > 用Nginx反向代理Node.js的方法

用Nginx反向代理Node.js的方法

2019年04月18日  | 移动技术网网络运营  | 我要评论

本文介绍了用nginx反向代理node.js的方法,分享给大家,具体如下:

安装pm2

npm install pm2 -g

ln -s /home/download/node-v8.11.1-linux-x64/lib/node_modules/pm2/bin/pm2 /usr/local/bin/pm2

修改package.json

"scripts": {
  "test": "echo \"error: no test specified\" && exit 1",
  "pm2": "/home/download/node-v8.11.1-linux-x64/lib/node_modules/pm2/bin/pm2 start /web/mazey.cn/server/app.js"
}

or

"scripts": {
  "test": "echo \"error: no test specified\" && exit 1",
  "pm2": "pm2 start app.js"
}

启动pm2

npm run pm2

开机启动pm2

pm2 save

pm2 startup centos

注意

若 pm2 startup centos 失败,可尝试 pm2 startup 。

pm2 detected systemv but you precised centos
 please verify that your choice is indeed your init system
 if you arent sure, just run : pm2 startup

修改nginx配置

vim /etc/nginx/conf.d/*.conf

upstream nodejs {
  server 127.0.0.1:3000;
  keepalive 64;
}
server {
  listen 80;
  server_name domain.cn;
  root /web/mazey.cn;
  index  index.htm;
  # 网站切到/server下时走nodejs
  location /server {
    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_set_header  connection "";
    proxy_pass http://nodejs;
  }
  location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
    expires 30d;
  }
  location ~ .*\.(js|css)?$ {
    expires 1h;
  }
}

相应的 app.js :

const express = require('express')
const app = express()
let hi = 'hi'

app.get('/server', (req, res, next) => {
 hi = `hello mazey!\n`
 next()
}, (req, res) => {
 res.send(`
 ${hi}
 ${req.method}\n
 ${req.originalurl}\n
 ${req.query.id}\n
 `)
})

const server = app.listen(3000, function () {
 let host = server.address().address
 let port = server.address().port

 console.log('example app listening at http://%s:%s', host, port)
})

注意

若报错 cannot get /xxx 说明 express 的路由没配好。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网