页面/_middleware.ts
import { NextRequest, NextResponse } from 'next/server';
const isMobile = (userAgent: string) =>
/iPhone|iPad|iPod|Android/i.test(userAgent);
const propName = 'x-rewrite';
enum Device {
desktop = 'no',
mobile = 'yes',
}
export function middleware(req: NextRequest) {
const userAgent = req.headers.get('user-agent');
const res = NextResponse.next();
if (userAgent) {
if (isMobile(userAgent)) {
res.headers.set(propName, Device.mobile);
console.log(res.headers, 'res');
return res;
} else {
res.headers.set(propName, Device.desktop);
return res;
}
}
}
next.config.js
async rewrites() {
return {
beforeFiles: [
{
source: '/football/livescore',
destination: '/football/livescore/mobile',
has: [
{
type: 'header',
key: 'x-rewrite',
value: '(?<rewrite>yes|true)',
},
],
},
{
source: '/football/livescore/:league',
destination: '/football/livescore/mobile/:league',
has: [
{
type: 'header',
key: 'x-rewrite',
value: '(?<rewrite>yes|true)',
},
],
},
],
};
},
https://github.com/vercel/next.js/discussions/37841在这里,我开始讨论我的问题。我试图用header
类型重写我的页面(更改目的地),但似乎不起作用。当我在浏览器上检查标题时,我会在标题中看到我的值,但它不起作用。
您可以从中间件本身使用NextResponse.rewrite
直接重写到移动路径,而不是在中间件中设置头并在next.config.js
中使用rewrites
。
import { NextRequest, NextResponse } from 'next/server';
const livescorePath = '/football/livescore';
const mobilePath = '/mobile'
const isMobile = (userAgent: string) => /iPhone|iPad|iPod|Android/i.test(userAgent);
export function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const userAgent = req.ua?.ua ?? '';
// Checks if path begins with `/football/livescore` and has mobile UA,
// then rewrites to mobile path if so
if (pathname.startsWith(livescorePath) && !pathname.includes(mobilePath) && isMobile(userAgent)) {
const league = pathname.replace(livescorePath, '');
req.nextUrl.pathname = `${livescorePath}${mobilePath}${league}`;
return NextResponse.rewrite(req.nextUrl);
}
return NextResponse.next();
}
import { NextRequest, NextResponse } from 'next/server';
const isMobile = (userAgent: string) =>
/iPhone|iPad|iPod|Android/i.test(userAgent);
export function middleware(req: NextRequest) {
const userAgent = req.headers.get('user-agent');
const { pathname, origin } = req.nextUrl;
if (userAgent && !pathname.includes('favicon.ico')) {
if (isMobile(userAgent)) {
return NextResponse.rewrite(`${origin}/mobile${pathname}`);
} else {
return NextResponse.rewrite(`${origin}/desktop${pathname}`);
}
}
}
也许它会有用,文件夹结构:
pages/mobile
pages/desktop