リダイレクト
Next.jsでリダイレクトを処理する方法はいくつかあります。このページでは、利用可能な各オプション、ユースケース、および多数のリダイレクトを管理する方法について説明します。
API | 目的 | 場所 | ステータスコード |
---|---|---|---|
useRouter | クライアントサイドナビゲーションの実行 | コンポーネント | 該当なし |
next.config.js におけるredirects | パスに基づいて受信リクエストをリダイレクトする | next.config.js ファイル | 307 (一時的) または 308 (永続的) |
NextResponse.redirect | 条件に基づいて受信リクエストをリダイレクトする | ミドルウェア | どこでも |
useRouter()
フック
コンポーネント内でリダイレクトする必要がある場合は、useRouter
フックの push
メソッドを使用できます。例:
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
)
}
参考情報:
- ユーザーをプログラムでナビゲートする必要がない場合は、
<Link>
コンポーネントを使用してください。
詳細については、useRouter
APIリファレンスを参照してください。
next.config.js
におけるredirects
next.config.js
ファイルの redirects
オプションを使用すると、受信リクエストパスを別の宛先パスにリダイレクトできます。これは、ページのURL構造を変更したり、事前にわかっているリダイレクトのリストがある場合に便利です。
redirects
は パス、ヘッダー、Cookie、およびクエリのマッチング をサポートしており、受信リクエストに基づいてユーザーをリダイレクトする柔軟性を提供します。
redirects
を使用するには、`next.config.js` ファイルにオプションを追加します。
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
async redirects() {
return [
// Basic redirect
{
source: '/about',
destination: '/',
permanent: true,
},
// Wildcard path matching
{
source: '/blog/:slug',
destination: '/news/:slug',
permanent: true,
},
]
},
}
export default nextConfig
詳細については、redirects
APIリファレンスを参照してください。
参考情報:
redirects
は、permanent
オプションを指定することで、307 (一時的リダイレクト) または 308 (永続的リダイレクト) のステータスコードを返すことができます。redirects
はプラットフォームによって制限がある場合があります。例えば、Vercelでは1,024件のリダイレクトという制限があります。多数のリダイレクト (1000件以上) を管理するには、ミドルウェアを使用したカスタムソリューションの作成を検討してください。詳細については、「大規模なリダイレクトの管理」を参照してください。redirects
はミドルウェアの前に実行されます。
MiddlewareにおけるNextResponse.redirect
ミドルウェアを使用すると、リクエストが完了する前にコードを実行できます。その後、受信リクエストに基づいて、NextResponse.redirect
を使用して別のURLにリダイレクトします。これは、条件 (例: 認証、セッション管理など) に基づいてユーザーをリダイレクトしたい場合や、多数のリダイレクトがある場合に便利です。
例えば、ユーザーが認証されていない場合に `/login` ページにリダイレクトするには:
import { NextResponse, NextRequest } from 'next/server'
import { authenticate } from 'auth-provider'
export function middleware(request: NextRequest) {
const isAuthenticated = authenticate(request)
// If the user is authenticated, continue as normal
if (isAuthenticated) {
return NextResponse.next()
}
// Redirect to login page if not authenticated
return NextResponse.redirect(new URL('/login', request.url))
}
export const config = {
matcher: '/dashboard/:path*',
}
参考情報:
- ミドルウェアは
next.config.js
のredirects
の後、レンダリングの前に実行されます。
詳細については、ミドルウェアのドキュメントを参照してください。
大規模なリダイレクトの管理 (高度な内容)
多数のリダイレクト (1000件以上) を管理するには、ミドルウェアを使用したカスタムソリューションの作成を検討できます。これにより、アプリケーションを再デプロイすることなく、リダイレクトをプログラムで処理できます。
これを行うには、以下を考慮する必要があります。
- リダイレクトマップの作成と保存。
- データ検索パフォーマンスの最適化。
Next.jsの例: 以下の推奨事項の実装については、ブルームフィルタを使用したミドルウェアの例を参照してください。
1. リダイレクトマップの作成と保存
リダイレクトマップは、データベース (通常はキーバリューストア) またはJSONファイルに保存できるリダイレクトのリストです。
次のデータ構造を検討してください。
{
"/old": {
"destination": "/new",
"permanent": true
},
"/blog/post-old": {
"destination": "/blog/post-new",
"permanent": true
}
}
ミドルウェアでは、VercelのEdge Config や Redis などのデータベースから読み取り、受信リクエストに基づいてユーザーをリダイレクトできます。
import { NextResponse, NextRequest } from 'next/server'
import { get } from '@vercel/edge-config'
type RedirectEntry = {
destination: string
permanent: boolean
}
export async function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname
const redirectData = await get(pathname)
if (redirectData && typeof redirectData === 'string') {
const redirectEntry: RedirectEntry = JSON.parse(redirectData)
const statusCode = redirectEntry.permanent ? 308 : 307
return NextResponse.redirect(redirectEntry.destination, statusCode)
}
// No redirect found, continue without redirecting
return NextResponse.next()
}
2. データ検索パフォーマンスの最適化
すべての受信リクエストに対して大規模なデータセットを読み取ることは、低速でコストがかかる場合があります。データ検索パフォーマンスを最適化するには、2つの方法があります。
- Vercel Edge Config や Redis のように、高速読み取りに最適化されたデータベースを使用します。
- ブルームフィルタのようなデータ検索戦略を使用して、より大きなリダイレクトファイルやデータベースを読み取る前に、リダイレクトが存在するかどうかを効率的にチェックします。
前の例を考慮すると、生成されたブルームフィルタファイルをミドルウェアにインポートし、受信リクエストのパス名がブルームフィルタに存在するかどうかを確認できます。
存在する場合、リクエストを次へ転送します。 実際のリダイレクトファイルを確認し、ユーザーを適切なURLにリダイレクトするAPIルート。これにより、大規模なリダイレクトファイルをミドルウェアにインポートして、すべての受信リクエストを遅くするのを回避できます。
import { NextResponse, NextRequest } from 'next/server'
import { ScalableBloomFilter } from 'bloom-filters'
import GeneratedBloomFilter from './redirects/bloom-filter.json'
type RedirectEntry = {
destination: string
permanent: boolean
}
// Initialize bloom filter from a generated JSON file
const bloomFilter = ScalableBloomFilter.fromJSON(GeneratedBloomFilter as any)
export async function middleware(request: NextRequest) {
// Get the path for the incoming request
const pathname = request.nextUrl.pathname
// Check if the path is in the bloom filter
if (bloomFilter.has(pathname)) {
// Forward the pathname to the Route Handler
const api = new URL(
`/api/redirects?pathname=${encodeURIComponent(request.nextUrl.pathname)}`,
request.nextUrl.origin
)
try {
// Fetch redirect data from the Route Handler
const redirectData = await fetch(api)
if (redirectData.ok) {
const redirectEntry: RedirectEntry | undefined =
await redirectData.json()
if (redirectEntry) {
// Determine the status code
const statusCode = redirectEntry.permanent ? 308 : 307
// Redirect to the destination
return NextResponse.redirect(redirectEntry.destination, statusCode)
}
}
} catch (error) {
console.error(error)
}
}
// No redirect found, continue the request without redirecting
return NextResponse.next()
}
その後、APIルートで
import type { NextApiRequest, NextApiResponse } from 'next'
import redirects from '@/app/redirects/redirects.json'
type RedirectEntry = {
destination: string
permanent: boolean
}
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const pathname = req.query.pathname
if (!pathname) {
return res.status(400).json({ message: 'Bad Request' })
}
// Get the redirect entry from the redirects.json file
const redirect = (redirects as Record<string, RedirectEntry>)[pathname]
// Account for bloom filter false positives
if (!redirect) {
return res.status(400).json({ message: 'No redirect' })
}
// Return the redirect entry
return res.json(redirect)
}
参考情報
- ブルームフィルタを生成するには、
bloom-filters
のようなライブラリを使用できます。- 悪意のあるリクエストを防ぐために、Route Handlerへのリクエストを検証する必要があります。
これは役に立ちましたか?