佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > 用Nginx反向代理Node.js的方法

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

熱門標(biāo)簽:美圖手機(jī) 檢查注冊表項(xiàng) 硅谷的囚徒呼叫中心 使用U盤裝系統(tǒng) 智能手機(jī) 網(wǎng)站建設(shè) 百度競價(jià)點(diǎn)擊價(jià)格的計(jì)算公式 阿里云

本文介紹了用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

開機(jī)啟動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)
})

注意

若報(bào)錯 Cannot GET /xxx 說明 Express 的路由沒配好。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

標(biāo)簽:湖北 通遼 煙臺 山南 湘潭 黃山 懷化 賀州

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《用Nginx反向代理Node.js的方法》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    连云港市| 哈尔滨市| 娄底市| 泽库县| 苍梧县| 呼和浩特市| 宜兴市| 颍上县| 施甸县| 乌鲁木齐市| 康保县| 夹江县| 阿坝| 西盟| 荣昌县| 海伦市| 广河县| 从化市| 基隆市| 夏津县| 深圳市| 综艺| 红河县| 祁阳县| 丰原市| 瑞安市| 高密市| 清远市| 赣州市| 乡城县| 红河县| 镇坪县| 从江县| 宜君县| 贵阳市| 崇州市| 丰原市| 蓬莱市| 昭平县| 高碑店市| 确山县|