[英]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.