记录nginx上部署nextjs

6,296 阅读1分钟

起因

商城的项目,需要提供一个商品详情的H5,去应对海关的报关检查。但原本toC的商城项目是单页面应用,海关的审核貌似是通过爬虫获取页面内容,那我们spa应用,完全爬不到内容,海关拿到的就是空白的页面。

于是使用了服务端渲染的nextjs框架,单独做了一个商品详情页

这里记录一下,在nginx上部署nextjs

1、在服务器上安装node、pm2

2、nextjs项目build

先执行一遍npm run build(next build)

3、增加一个package.json的scripts

  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "pm2start": "pm2 start npm --name shishikangh5 -- run start" // 这里
  },

把这个任务命名为shishikangh5,并执行npm run start

4、nginx中nextjs相关配置

    # nextjs
    location /h5 {
        # proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;
        # 关键代码 nextjs起服务的端口
        proxy_pass http://***.***.***:3000/; 
        proxy_redirect off;
    }
    # 关键代码 让nextjs页面可以访问js、css、图片等文件
    location /_next/static/ {
	  alias /root/nginx/html/shishikang/goodsDetailH5/.next/static/;
    }

5、进入服务器上的项目目录

执行

npm run pm2start // 使用pm2 启动项目

pm2 list // 查看任务进程
pm2 stop shishikangh5 // 停止任务

附:
pm2常用命令