Next.js: 根据请求主机呈现自定义的动态页面

Next.js: Render dynamic pages customized based on requesting host

我想根据请求页面的域呈现具有自定义内容/样式的动态 next.js 页面。 基本上 运行 一个 next.js 多个域下的应用程序。

我知道我必须进行某种自定义路由,但不确切知道如何以及如何将主机信息传递到请求的页面,因此它从数据库中获取匹配数据。

您应该能够在您的 pages/_app.jsx 文件 static getInitialProps(context) 方法中验证这一点,并使用 context 验证请求的来源然后 return 一个标志到组件。

示例:

// pages/_app.js

import app from 'next/app';

export default class MyApp extends app {
  static getInitialProps({ Component, router, ctx }) {
    let pageProps = app.getInitialProps({ Component, router, ctx });

    if (ctx.req.headers.host.match(/localhost/)) {
      pageProps = {
        ...pageProps,
        renderFrom: 'mydomain',
      }
    }

    return { pageProps };
  }

  render() {
    const { Component, pageProps } = this.props;
    return (
      <section id="app">
        <Component {...pageProps} />
      </section>
    );
  }
}

请注意,我调用 app.getInitialProps 来模仿源代码中的 next/app 组件行为 here

在您的 pages/index.js 中,您将可以访问 props.renderFrom 并在那里显示数据。

// pages/index.js

import React from 'react'

const Home = props => (
  <div>
    Rendering content for domain: {props.renderFrom}
  </div>
)

export default Home

由于您在 _app.js 中验证请求的来源,因此此 属性 将在您的所有容器(页面)中可用,因此您可以为您的应用程序使用相同的路由并只渲染数据不同。

提示:您还可以使用 next-routes 来管理应用程序的路由,它比 next 附带的更好,并且在这里您有一个自定义服务器,您也可以在其中管理您的流量。

希望这对您有所帮助并为您指明正确的方向。

这是在同一 Next.js 站点 上托管 多个域的示例(同时维护 多种语言 和静态站点 generation/SSG), 使用 Next.js' i18n 系统:

https://github.com/tomsoderlund/nextjs-multi-domain-locale