检索 Next.js 页面中的子域
Retrieving sub-domain in Next.js page
我有一个 pages/index.tsx
Next.js 页面,其代码如下所示:
import { ApolloProvider } from "@apollo/react-hooks"
import Client from "../db"
import Header from "../components/Header"
export default function Index() {
return <ApolloProvider client={Client}>
<Header langKey={langKey} />
</ApolloProvider>
}
问题是,langKey
应该是访问页面的子域(例如,en.localhost:3000
或 fr.localhost:3000
;langKey
会en
或 fr
)。如何从 Next.js 上下文中检索此信息?我尝试了 Router 对象,但它看起来不像在第一个 /
.
之前存储任何 URL 信息
在 getInitialProps
生命周期方法 (doc's here) 上,您可以在 server-side 上访问请求 object 并解析主机 header。
Index.getInitialProps = async ({ req }) => {
const subdomain = req.headers.host.split('.')[0];
return { langkey: subdomain };
};
如果只有客户端需要此信息,您可以在生命周期方法中的某处轻松解析 window.location
:window.location.host.split('.')[0]
.
希望对您有所帮助!
我 运行 最近遇到了类似的问题,并找到了一个不同的简单解决方案:您可以使用 rewrites 将主机名作为路径变量放入路径中。这适用于服务器端和客户端,尽管我只对使用 getStaticPaths
/getStaticProps
的页面进行了测试;其他类型的页面呈现可能存在问题。
只需在 next.config.js
中添加这样的内容即可:
rewrites: async () => {
// In order to support wildcard subdomains with different content, use a "rewrite" to include the host in the path
return [
{
source: '/:path*{/}?',
has: [
{
type: 'host',
value: '(?<siteHost>.*)',
},
],
destination: '/site/:siteHost/:path*',
},
];
},
注意 1:仅当初始请求与 /pages/
中的文件不匹配时才使用此重写,因此要对其进行测试,您需要将现有内容移动到 site
子文件夹中,例如将 pages/index.tsx
移动到 pages/site/[siteHost]/index.tsx
注意 2:由于 https://github.com/vercel/next.js/issues/14930,使用 source: '/:path*'
不适用于主页 (/
) - 这就是使用 source: '/:path*{/}?'
的原因
我有一个 pages/index.tsx
Next.js 页面,其代码如下所示:
import { ApolloProvider } from "@apollo/react-hooks"
import Client from "../db"
import Header from "../components/Header"
export default function Index() {
return <ApolloProvider client={Client}>
<Header langKey={langKey} />
</ApolloProvider>
}
问题是,langKey
应该是访问页面的子域(例如,en.localhost:3000
或 fr.localhost:3000
;langKey
会en
或 fr
)。如何从 Next.js 上下文中检索此信息?我尝试了 Router 对象,但它看起来不像在第一个 /
.
在 getInitialProps
生命周期方法 (doc's here) 上,您可以在 server-side 上访问请求 object 并解析主机 header。
Index.getInitialProps = async ({ req }) => {
const subdomain = req.headers.host.split('.')[0];
return { langkey: subdomain };
};
如果只有客户端需要此信息,您可以在生命周期方法中的某处轻松解析 window.location
:window.location.host.split('.')[0]
.
希望对您有所帮助!
我 运行 最近遇到了类似的问题,并找到了一个不同的简单解决方案:您可以使用 rewrites 将主机名作为路径变量放入路径中。这适用于服务器端和客户端,尽管我只对使用 getStaticPaths
/getStaticProps
的页面进行了测试;其他类型的页面呈现可能存在问题。
只需在 next.config.js
中添加这样的内容即可:
rewrites: async () => {
// In order to support wildcard subdomains with different content, use a "rewrite" to include the host in the path
return [
{
source: '/:path*{/}?',
has: [
{
type: 'host',
value: '(?<siteHost>.*)',
},
],
destination: '/site/:siteHost/:path*',
},
];
},
注意 1:仅当初始请求与 /pages/
中的文件不匹配时才使用此重写,因此要对其进行测试,您需要将现有内容移动到 site
子文件夹中,例如将 pages/index.tsx
移动到 pages/site/[siteHost]/index.tsx
注意 2:由于 https://github.com/vercel/next.js/issues/14930,使用 source: '/:path*'
不适用于主页 (/
) - 这就是使用 source: '/:path*{/}?'