如何使用Nginx反向代理Node.js?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
10余年的皇姑網(wǎng)站建設(shè)經(jīng)驗(yàn),針對(duì)設(shè)計(jì)、前端、開(kāi)發(fā)、售后、文案、推廣等六對(duì)一服務(wù),響應(yīng)快,48小時(shí)及時(shí)工作處理。成都營(yíng)銷網(wǎng)站建設(shè)的優(yōu)勢(shì)是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動(dòng)調(diào)整皇姑建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無(wú)論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計(jì),從而大程度地提升瀏覽體驗(yàn)。創(chuàng)新互聯(lián)公司從事“皇姑網(wǎng)站設(shè)計(jì)”,“皇姑網(wǎng)站推廣”以來(lái),每個(gè)客戶項(xiàng)目都認(rèn)真落實(shí)執(zhí)行。
安裝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" }
啟動(dòng)pm2
npm run pm2
開(kāi)機(jī)啟動(dòng)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; # 網(wǎng)站切到/server下時(shí)走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; } }
相應(yīng)的 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) })
關(guān)于如何使用Nginx反向代理Node.js問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。