06-redirecting
Redirecting
Next.js에서 리디렉션을 처리할 수 있는 몇 가지 방법이 있습니다. 이 페이지에서는 사용 가능한 각 옵션, 사용 사례 및 대량의 리디렉션을 관리하는 방법을 살펴봅니다.
| API | 목적 | 어디에서(where) | 상태 코드 |
|---|---|---|---|
redirect | 변경 또는 이벤트 발생 후 사용자 리디렉션 | 서버 컴포넌트, 서버 액션, 라우트 핸들러 | 307(임시) 또는 303(서버 동작) |
permanentRedirect | 변경 또는 이벤트 발생 후 사용자 리디렉션 | 서버 컴포넌트, 서버 액션, 라우트 핸들러 | 308 (Permanent) |
useRouter | 클라이언트 측 탐색 수행 | 클라이언트 컴포넌트의 이벤트 핸들러 | N/A |
redirects in next.config.js | 경로를 기반으로 들어오는 요청 리디렉션 | next.config.js file | 307(임시) 또는 308(영구) |
NextResponse.redirect | 조건에 따라 수신 요청 리디렉션하기 | Middleware | Any |
1. redirect 함수
리디렉션 기능을 사용하면 사용자를 다른 URL로 리디렉션할 수 있습니다.
서버 컴포넌트, 라우트 핸들러, 서버 액션에서 리디렉션을 호출할 수 있습니다.
리디렉션은 종종 변경이나 이벤트 이후에 사용됩니다. 예를 들어, 글 작성과 같은 경우입니다:
1'use server'23import { redirect } from 'next/navigation'4import { revalidatePath } from 'next/cache'56export async function createPost(id: string) {7try {8// Call database9} catch (error) {10// Handle errors11}1213revalidatePath('/posts') // Update cached posts14redirect(`/post/${id}`) // Navigate to the new post page15}
알아두면 유용합니다:
redirect는 기본적으로 307(임시 리디렉션) 상태 코드를 반환합니다.
- 서버 액션에서 사용하면 303(기타 참조)을 반환하며,
- 이는 일반적으로 POST 요청의 결과로 성공 페이지로 리디렉션하는 데 사용됩니다.
redirect는 내부적으로 오류를 발생시키므로 시도/잡기 블록 외부에서 호출해야 합니다.redirect는 렌더링 프로세스 중 클라이언트 컴포넌트에서 호출할 수 있지만 이벤트 핸들러에서는 호출할 수 없습니다.
- 대신
useRouter 훅을 사용할 수 있습니다.redirect는 절대 URL도 허용하며 외부 링크로 리디렉션하는 데 사용할 수 있습니다.- 렌더링 프로세스 전에 리디렉션하려면
next.config.js또는미들웨어를 사용하세요.
자세한 내용은 redirect API 참조 를 참조하세요.
2. permanentRedirect 함수
permanentRedirect 함수를 사용하면 사용자를 다른 URL로 영구적으로 리디렉션할 수 있습니다.
서버 컴포넌트, 라우트 핸들러, 서버 액션에서 permanentRedirect을 호출할 수 있습니다.
permanentRedirect은 사용자 이름을 변경한 후 사용자의 프로필 URL을 업데이트하는 등
엔티티의 정식 URL을 변경하는 변경 또는 이벤트 후에 자주 사용됩니다:
1'use server'23import { permanentRedirect } from 'next/navigation'4import { revalidateTag } from 'next/cache'56export async function updateUsername(username: string, formData: FormData) {7try {8// Call database9} catch (error) {10// Handle errors11}1213revalidateTag('username') // Update all references to the username14permanentRedirect(`/profile/${username}`) // Navigate to the new user profile15}
알아두면 유용합니다:
permanentRedirect은 기본적으로 308(영구 리디렉션) 상태 코드를 반환합니다.permanentRedirect은 절대 URL도 허용하며 외부 링크로 리디렉션하는 데 사용할 수 있습니다.- 렌더링 프로세스 전에 리디렉션하려면,
next.config.js또는미들웨어를 사용하세요.
자세한 내용은 permanentRedirect API 참조를 참조하세요.
3. useRouter() 훅
클라이언트 컴포넌트의 이벤트 핸들러 내부에서 리디렉션해야 하는 경우, useRouter hook의 push 메서드를 사용할 수 있습니다. 예를 들어
1'use client'23import { useRouter } from 'next/navigation'45export default function Page() {6const router = useRouter()78return (9<button type="button" onClick={() => router.push('/dashboard')}>10Dashboard11</button>12)13}
알아두면 유용합니다:
사용자를 프로그래밍 방식으로 탐색할 필요가 없는 경우,
<Link>컴포넌트를 사용해야 합니다.
자세한 내용은 useRouter API 참조를 참조하세요.
4. next.config.js 안의 redirects
next.config.js 파일의 redirects 옵션을 사용하면 들어오는 요청 경로를 다른 대상 경로로 리디렉션할 수 있습니다.
페이지의 URL 구조를 변경하거나 미리 알고 있는 리디렉션 목록이 있을 때 유용합니다.
redirects은 경로, 헤더, 쿠키, 쿼리 매칭을 지원하므로 수신 요청에 따라 유연하게 사용자를 리디렉션할 수 있습니다.
redirects을 사용하려면, next.config.js 파일에 옵션을 추가하세요:
1module.exports = {2async redirects() {3return [4// Basic redirect5{6source: '/about',7destination: '/',8permanent: true,9},10// Wildcard path matching11{12source: '/blog/:slug',13destination: '/news/:slug',14permanent: true,15},16]17},18}
자세한 내용은 redirects API 참조를 참조하세요.
알아두면 유용합니다:
redirects은 영구 옵션으로 307(임시 리디렉션) 또는 308(영구 리디렉션) 상태 코드를 반환할 수 있습니다.redirects은 플랫폼에 따라 제한이 있을 수 있습니다.
- 예를 들어, Vercel에서는 리디렉션 수가 1,024개로 제한되어 있습니다.
- 많은 수의 리디렉션(1000개 이상)을 관리하려면,
미들웨어를 사용하여 사용자 지정 솔루션을 만드는 것을 고려하세요.- 자세한 내용은
대규모 리디렉션 관리하기절을 참조하세요.redirects은 미들웨어보다 먼저 실행됩니다.
5. Middleware 안의 NextResponse.redirect
미들웨어를 사용하면 요청이 완료되기 전에 코드를 실행할 수 있습니다.
그런 다음 들어오는 요청에 따라 NextResponse.redirect를 사용하여 다른 URL로 리디렉션합니다.
이는 조건(예: 인증, 세션 관리 등)에 따라 사용자를 리디렉션하거나 리디렉션 횟수가 많을 때 유용합니다.
예를 들어, 사용자가 인증되지 않은 경우 /login 페이지로 리디렉션합니다:
1import { NextResponse, NextRequest } from 'next/server'2import { authenticate } from 'auth-provider'34export function middleware(request: NextRequest) {5const isAuthenticated = authenticate(request)67// If the user is authenticated, continue as normal8if (isAuthenticated) {9return NextResponse.next()10}1112// Redirect to login page if not authenticated13return NextResponse.redirect(new URL('/login', request.url))14}1516export const config = {17matcher: '/dashboard/:path*',18}
알아두면 유용합니다:
미들웨어는
next.config.js의redirects후 렌더링 전에 실행됩니다.
자세한 내용은 미들웨어 설명서를 참조하세요.
6. 대규모 리디렉션 관리(고급)
많은 수의 리디렉션(1000개 이상)을 관리하려면 미들웨어를 사용하여 사용자 지정 솔루션을 만드는 것을 고려할 수 있습니다. 이렇게 하면, 애플리케이션을 다시 배포할 필요 없이 프로그래밍 방식으로 리디렉션을 처리할 수 있습니다.
이렇게 하려면 다음 사항을 고려해야 합니다:
- 리디렉션 맵 생성 및 저장.
- 데이터 조회 성능 최적화.
Next.js 예제: 아래 권장 사항의 구현에 대한 예제는 Bloom 필터가 포함된 미들웨어 예제 를 참조하세요.
6.1 리디렉션 맵 생성 및 저장
리디렉션 맵은 데이터베이스(일반적으로 키-값 저장소) 또는 JSON 파일에 저장할 수 있는 리디렉션 목록입니다.
다음 데이터 구조를 고려하세요:
1{2"/old": {3"destination": "/new",4"permanent": true5},6"/blog/post-old": {7"destination": "/blog/post-new",8"permanent": true9}10}
미들웨어에서는, Vercel의 Edge Config 또는 Redis와 같은 데이터베이스에서 읽고 들어오는 요청에 따라 사용자를 리디렉션할 수 있습니다:
1import { NextResponse, NextRequest } from 'next/server'2import { get } from '@vercel/edge-config'34type RedirectEntry = {5destination: string6permanent: boolean7}89export async function middleware(request: NextRequest) {10const pathname = request.nextUrl.pathname11const redirectData = await get(pathname)1213if (redirectData && typeof redirectData === 'string') {14const redirectEntry: RedirectEntry = JSON.parse(redirectData)15const statusCode = redirectEntry.permanent ? 308 : 30716return NextResponse.redirect(redirectEntry.destination, statusCode)17}1819// No redirect found, continue without redirecting20return NextResponse.next()21}
6.2 데이터 조회 성능 최적화
들어오는 모든 요청에 대해 대규모 데이터 집합을 읽는 것은 느리고 비용이 많이 들 수 있습니다. 데이터 조회 성능을 최적화할 수 있는 두 가지 방법이 있습니다:
- 빠른 읽기에 최적화된 데이터베이스(예: Vercel Edge Config 또는 Redis)를 사용합니다.
- 블룸 필터와 같은 데이터 조회 전략을 사용하여 더 큰 리디렉션 파일이나 데이터베이스를 읽기 전에 리디렉션이 존재하는지 효율적으로 확인합니다.
앞의 예시를 고려하면 생성된 블룸 필터 파일을 미들웨어로 가져온 다음 들어오는 요청 경로명이 블룸 필터에 존재하는지 확인할 수 있습니다.
존재하는 경우 실제 파일을 확인하고 사용자를 적절한 URL로 리디렉션하는 라우트 핸들러 로 요청을 전달합니다. 이렇게 하면 모든 수신 요청의 속도를 저하시킬 수 있는 대용량 리디렉션 파일을 미들웨어로 가져오는 것을 방지할 수 있습니다.
1import { NextResponse, NextRequest } from 'next/server'2import { ScalableBloomFilter } from 'bloom-filters'3import GeneratedBloomFilter from './redirects/bloom-filter.json'45type RedirectEntry = {6destination: string7permanent: boolean8}910// Initialize bloom filter from a generated JSON file11const bloomFilter = ScalableBloomFilter.fromJSON(GeneratedBloomFilter as any)1213export async function middleware(request: NextRequest) {14// Get the path for the incoming request15const pathname = request.nextUrl.pathname1617// Check if the path is in the bloom filter18if (bloomFilter.has(pathname)) {19// Forward the pathname to the Route Handler20const api = new URL(21`/api/redirects?pathname=${encodeURIComponent(request.nextUrl.pathname)}`,22request.nextUrl.origin,23)2425try {26// Fetch redirect data from the Route Handler27const redirectData = await fetch(api)2829if (redirectData.ok) {30const redirectEntry: RedirectEntry | undefined = await redirectData.json()3132if (redirectEntry) {33// Determine the status code34const statusCode = redirectEntry.permanent ? 308 : 3073536// Redirect to the destination37return NextResponse.redirect(redirectEntry.destination, statusCode)38}39}40} catch (error) {41console.error(error)42}43}4445// No redirect found, continue the request without redirecting46return NextResponse.next()47}
그런 다음 Route Handler에서:
1import { NextRequest, NextResponse } from 'next/server'2import redirects from '@/app/redirects/redirects.json'34type RedirectEntry = {5destination: string6permanent: boolean7}89export function GET(request: NextRequest) {10const pathname = request.nextUrl.searchParams.get('pathname')11if (!pathname) {12return new Response('Bad Request', { status: 400 })13}1415// Get the redirect entry from the redirects.json file16const redirect = (redirects as Record<string, RedirectEntry>)[pathname]1718// Account for bloom filter false positives19if (!redirect) {20return new Response('No redirect', { status: 400 })21}2223// Return the redirect entry24return NextResponse.json(redirect)25}
알아두면 유용합니다:
bloom-filters를 생성하려면 블룸 필터와 같은 라이브러리를 사용할 수 있니다.- 악의적인 요청을 방지하기 위해 라우트 핸들러에 대한 요청의 유효성을 검사해야 합니다.