用Nginx反向代理Node.js的方法
本文介绍了用Nginx反向代理Node.js的方法,分享给大家,具体如下:
安装pm2
npminstallpm2-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:notestspecified\"&&exit1",
"pm2":"/home/download/node-v8.11.1-linux-x64/lib/node_modules/pm2/bin/pm2start/web/mazey.cn/server/app.js"
}
or
"scripts":{
"test":"echo\"Error:notestspecified\"&&exit1",
"pm2":"pm2startapp.js"
}
启动pm2
npmrunpm2
开机启动pm2
pm2save pm2startupcentos
注意
若pm2startupcentos失败,可尝试pm2startup。
PM2detectedsystemvbutyouprecisedcentos Pleaseverifythatyourchoiceisindeedyourinitsystem Ifyouarentsure,justrun:pm2startup
修改Nginx配置
vim/etc/nginx/conf.d/*.conf
upstreamnodejs{
server127.0.0.1:3000;
keepalive64;
}
server{
listen80;
server_namedomain.cn;
root/web/mazey.cn;
indexindex.htmlindex.htm;
#网站切到/server下时走nodejs
location/server{
proxy_set_headerX-Real-IP$remote_addr;
proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;
proxy_set_headerHost$http_host;
proxy_set_headerX-Nginx-Proxytrue;
proxy_set_headerConnection"";
proxy_passhttp://nodejs;
}
location~.*\.(gif|jpg|jpeg|png|bmp|swf)${
expires30d;
}
location~.*\.(js|css)?${
expires1h;
}
}
相应的app.js:
constexpress=require('express')
constapp=express()
lethi='hi'
app.get('/server',(req,res,next)=>{
hi=`HelloMazey!\n`
next()
},(req,res)=>{
res.send(`
${hi}
${req.method}\n
${req.originalUrl}\n
${req.query.id}\n
`)
})
constserver=app.listen(3000,function(){
lethost=server.address().address
letport=server.address().port
console.log('Exampleapplisteningathttp://%s:%s',host,port)
})
注意
若报错CannotGET/xxx说明Express的路由没配好。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下