【问题标题】:How to set relative path for a reverse proxy nextjs server如何为反向代理 nextjs 服务器设置相对路径
【发布时间】:2019-12-11 14:42:57
【问题描述】:

我有两台服务器 A 和 B,它们都托管在 AWS 上。 A 的规则是 /v2//v2 发送到 B。这很好用。 ServerB 是一个使用 nginx 和 express 的 NextJs 应用。

所有路由都以/v2/ 开头,所以/v2/foo 显示一个页面。该页面给出了200 的响应,但没有资产。服务器B 具有私有 IP 和公共 IP,并且转到 B:<IP>/v2/foo 的任一 IP 地址,资产加载正常。从A 去那里:<IP>/v2/foo,资产不加载所以我假设相对路径问题?

我找到了this example关于如何设置setAssetPrefix

// server.js

 const express = require('express')
const compression = require('compression');
const next = require('next')
const bodyParser = require('body-parser')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare()
.then(() => {
  const server = express()
  // Not sure what this does
  app.setAssetPrefix('/v2') //??
  server.use(compression())
  server.use(bodyParser.json())
  server.use(bodyParser.urlencoded({ extended: true }))

  server.get('/v2/foo', function(req, res) {
    app.render(req, res, '/v2/foo', {})
  })


  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, (err) => {
    if (err) throw err
    console.log(`> Ready on ${process.env.HOST}`)
  })

})
.catch((ex) => {
  console.error(ex.stack)
  process.exit(1)
})

使用服务器 B 的私有和公共 IP 地址可以正常工作,但是当使用服务器 A 的 url 时,页面会点击但没有样式。主页使用“css in js”并且工作正常但不是/v2/foo使用import ../../master.scss

next.config.js:

const sass = require('@zeit/next-sass')
const css = require('@zeit/next-css')
const withPlugins = require("next-compose-plugins")

const nextConfig = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      use: ['@svgr/webpack'],
    });

    return config;
  }
}

//https://github.com/zeit/next-plugins/issues/266#issuecomment-474721942
module.exports = withPlugins([
  [sass],
  [css, { cssModules: false, url: false }]
], nextConfig);

nginx:

server {
        listen 80;
        listen [::]:80;

        root /var/www/v2/html/dist;
        #index index.html index.htm index.nginx-debian.html;

        server_name <public_IP> <private_IP> <server_A_domain>;

        location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        }
}

【问题讨论】:

标签: reactjs next.js


【解决方案1】:

尝试通过将proxy_pass_request_headers on; 添加到location 块来传递所有标题

【讨论】:

  • 谢谢。不工作。我需要能够更改资产路径/url/域,并且应该这样做。
【解决方案2】:

您可以创建自定义 Express.js 服务器:

server.js

const express = require('express')
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const env = process.env.NODE_ENV || 'development'
const dev = env !== 'production'
const app = next({
  dir: '.', // base directory where everything is, could move to src later
  dev,
})

const handle = app.getRequestHandler()

let server

app
  .prepare()
  .then(() => {
    server = express()

    // Set up the proxy.
    if (dev) {
      const { createProxyMiddleware } = require('http-proxy-middleware')
      server.use(
        '/api',
        createProxyMiddleware({
          target: 'https://api.staging.gocrypto.com/',
          changeOrigin: true,
          cookieDomainRewrite: 'localhost',
          logLevel: 'debug',
        })
      )
    }

    // Default catch-all handler to allow Next.js to handle all other routes
    server.all('*', (req, res) => handle(req, res))

    server.listen(port, err => {
      if (err) {
        throw err
      }
      console.log(`> Ready on port ${port} [${env}]`)
    })
  })
  .catch(err => {
    console.log('An error occurred, unable to start the server')
    console.log(err)
  })

不要忘记将您的 cookie(如果您正在使用会话)重写为 localhost:

cookieDomainRewrite: 'localhost'

然后在package.json中添加一个脚本:

"scripts": {
    "dev": "node devServer.js",
    "build": "next build",
    "start": "next start",
  },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2016-09-14
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    相关资源
    最近更新 更多