![](/img/trans.png)
[英]How to use custom fonts on a Next.js app under a sub-path of a domain?
[英]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 信息。
我最近遇到了类似的问题,并找到了一个不同的简单解决方案:您可以使用 重写将主机名作为路径变量放入路径中。 这适用于服务器端和客户端,尽管我只用使用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*{/}?'
在getInitialProps
生命周期方法( 此处为doc )上,您可以在服务器端访问请求对象并解析主机标头。
Index.getInitialProps = async ({ req }) => {
const subdomain = req.headers.host.split('.')[0];
return { langkey: subdomain };
};
如果仅在客户端需要此信息,则可以使用以下方法轻松地在生命周期方法中的某个位置解析window.location
: window.location.host.split('.')[0]
。
希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.