[英]How to use Nextjs middleware to redirect users to sub-domain based on IP
我试图弄清楚如何正确使用 NextJs 的中间件将用户从特定国家路由到另一个 web 域,但我无法让它正常工作。 以下是我的设置:
主域: https://www.example.com子域: https://ca.example.Z4D236D9A2DFEDAD4BEC0C05C0
src/middleware.js
import { NextResponse } from "next/server";
export function middleware(req) {
const { nextUrl: geo } = req;
const country = geo.country;
if (country === "CA") {
return NextResponse.redirect(new URL(`https://ca.example.com`));
}
}
以上不起作用,我感觉我可能误解了中间件在我的用例中是如何工作的。 任何指针将不胜感激!
好的,我自己想通了。 我已经简化了代码,它现在可以工作了
import { NextResponse } from "next/server";
export function middleware(req) {
const country = req.geo.country;
if (country === "CA") {
return NextResponse.redirect("https://ca.example.com");
} else {
return;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.