如何使用Nginx反向代理Node.js?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

10余年的皇姑网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。成都营销网站建设的优势是能够根据用户设备显示端的尺寸不同,自动调整皇姑建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联公司从事“皇姑网站设计”,“皇姑网站推广”以来,每个客户项目都认真落实执行。
安装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.html 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)
})关于如何使用Nginx反向代理Node.js问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。