Skip to Content
FrontendNextJsRouting06-redirecting

Redirecting

Next.js에서 리디렉션을 처리할 수 있는 몇 가지 방법이 있습니다. 이 페이지에서는 사용 가능한 각 옵션, 사용 사례 및 대량의 리디렉션을 관리하는 방법을 살펴봅니다.

API목적어디에서(where)상태 코드
redirect변경 또는 이벤트 발생 후 사용자 리디렉션서버 컴포넌트, 서버 액션, 라우트 핸들러307(임시) 또는 303(서버 동작)
permanentRedirect변경 또는 이벤트 발생 후 사용자 리디렉션서버 컴포넌트, 서버 액션, 라우트 핸들러308 (Permanent)
useRouter클라이언트 측 탐색 수행클라이언트 컴포넌트의 이벤트 핸들러N/A
redirects in next.config.js경로를 기반으로 들어오는 요청 리디렉션next.config.js file307(임시) 또는 308(영구)
NextResponse.redirect조건에 따라 수신 요청 리디렉션하기MiddlewareAny

1. redirect 함수

리디렉션 기능을 사용하면 사용자를 다른 URL로 리디렉션할 수 있습니다. 서버 컴포넌트, 라우트 핸들러, 서버 액션에서 리디렉션을 호출할 수 있습니다.

리디렉션은 종종 변경이나 이벤트 이후에 사용됩니다. 예를 들어, 글 작성과 같은 경우입니다:

app/actions.tsx
1
'use server'
2
3
import { redirect } from 'next/navigation'
4
import { revalidatePath } from 'next/cache'
5
6
export async function createPost(id: string) {
7
try {
8
// Call database
9
} catch (error) {
10
// Handle errors
11
}
12
13
revalidatePath('/posts') // Update cached posts
14
redirect(`/post/${id}`) // Navigate to the new post page
15
}

알아두면 유용합니다:

  • redirect는 기본적으로 307(임시 리디렉션) 상태 코드를 반환합니다.
    • 서버 액션에서 사용하면 303(기타 참조)을 반환하며,
    • 이는 일반적으로 POST 요청의 결과로 성공 페이지로 리디렉션하는 데 사용됩니다.
  • redirect는 내부적으로 오류를 발생시키므로 시도/잡기 블록 외부에서 호출해야 합니다.
  • redirect는 렌더링 프로세스 중 클라이언트 컴포넌트에서 호출할 수 있지만 이벤트 핸들러에서는 호출할 수 없습니다.
    • 대신 useRouter 훅을 사용할 수 있습니다.
  • redirect는 절대 URL도 허용하며 외부 링크로 리디렉션하는 데 사용할 수 있습니다.
  • 렌더링 프로세스 전에 리디렉션하려면 next.config.js 또는 미들웨어를 사용하세요.

자세한 내용은 redirect API 참조 를 참조하세요.


2. permanentRedirect 함수

permanentRedirect 함수를 사용하면 사용자를 다른 URL로 영구적으로 리디렉션할 수 있습니다. 서버 컴포넌트, 라우트 핸들러, 서버 액션에서 permanentRedirect을 호출할 수 있습니다.

permanentRedirect은 사용자 이름을 변경한 후 사용자의 프로필 URL을 업데이트하는 등 엔티티의 정식 URL을 변경하는 변경 또는 이벤트 후에 자주 사용됩니다:

app/actions.ts
1
'use server'
2
3
import { permanentRedirect } from 'next/navigation'
4
import { revalidateTag } from 'next/cache'
5
6
export async function updateUsername(username: string, formData: FormData) {
7
try {
8
// Call database
9
} catch (error) {
10
// Handle errors
11
}
12
13
revalidateTag('username') // Update all references to the username
14
permanentRedirect(`/profile/${username}`) // Navigate to the new user profile
15
}

알아두면 유용합니다:

  • permanentRedirect은 기본적으로 308(영구 리디렉션) 상태 코드를 반환합니다.
  • permanentRedirect은 절대 URL도 허용하며 외부 링크로 리디렉션하는 데 사용할 수 있습니다.
  • 렌더링 프로세스 전에 리디렉션하려면, next.config.js 또는 미들웨어를 사용하세요.

자세한 내용은 permanentRedirect API 참조를 참조하세요.


3. useRouter() 훅

클라이언트 컴포넌트의 이벤트 핸들러 내부에서 리디렉션해야 하는 경우, useRouter hook의 push 메서드를 사용할 수 있습니다. 예를 들어

app/page.tsx
1
'use client'
2
3
import { useRouter } from 'next/navigation'
4
5
export default function Page() {
6
const router = useRouter()
7
8
return (
9
<button type="button" onClick={() => router.push('/dashboard')}>
10
Dashboard
11
</button>
12
)
13
}

알아두면 유용합니다:

사용자를 프로그래밍 방식으로 탐색할 필요가 없는 경우, <Link> 컴포넌트를 사용해야 합니다.

자세한 내용은 useRouter API 참조를 참조하세요.


4. next.config.js 안의 redirects

next.config.js 파일의 redirects 옵션을 사용하면 들어오는 요청 경로를 다른 대상 경로로 리디렉션할 수 있습니다. 페이지의 URL 구조를 변경하거나 미리 알고 있는 리디렉션 목록이 있을 때 유용합니다.

redirects은 경로, 헤더, 쿠키, 쿼리 매칭을 지원하므로 수신 요청에 따라 유연하게 사용자를 리디렉션할 수 있습니다.

redirects을 사용하려면, next.config.js 파일에 옵션을 추가하세요:

next.config.js
1
module.exports = {
2
async redirects() {
3
return [
4
// Basic redirect
5
{
6
source: '/about',
7
destination: '/',
8
permanent: true,
9
},
10
// Wildcard path matching
11
{
12
source: '/blog/:slug',
13
destination: '/news/:slug',
14
permanent: true,
15
},
16
]
17
},
18
}

자세한 내용은 redirects API 참조를 참조하세요.

알아두면 유용합니다:

  • redirects은 영구 옵션으로 307(임시 리디렉션) 또는 308(영구 리디렉션) 상태 코드를 반환할 수 있습니다.
  • redirects은 플랫폼에 따라 제한이 있을 수 있습니다.
    • 예를 들어, Vercel에서는 리디렉션 수가 1,024개로 제한되어 있습니다.
    • 많은 수의 리디렉션(1000개 이상)을 관리하려면, 미들웨어를 사용하여 사용자 지정 솔루션을 만드는 것을 고려하세요.
    • 자세한 내용은 대규모 리디렉션 관리하기절을 참조하세요.
  • redirects은 미들웨어보다 먼저 실행됩니다.

5. Middleware 안의 NextResponse.redirect

미들웨어를 사용하면 요청이 완료되기 전에 코드를 실행할 수 있습니다. 그런 다음 들어오는 요청에 따라 NextResponse.redirect를 사용하여 다른 URL로 리디렉션합니다. 이는 조건(예: 인증, 세션 관리 등)에 따라 사용자를 리디렉션하거나 리디렉션 횟수가 많을 때 유용합니다.

예를 들어, 사용자가 인증되지 않은 경우 /login 페이지로 리디렉션합니다:

middleware.ts
1
import { NextResponse, NextRequest } from 'next/server'
2
import { authenticate } from 'auth-provider'
3
4
export function middleware(request: NextRequest) {
5
const isAuthenticated = authenticate(request)
6
7
// If the user is authenticated, continue as normal
8
if (isAuthenticated) {
9
return NextResponse.next()
10
}
11
12
// Redirect to login page if not authenticated
13
return NextResponse.redirect(new URL('/login', request.url))
14
}
15
16
export const config = {
17
matcher: '/dashboard/:path*',
18
}

알아두면 유용합니다:

미들웨어는 next.config.js의 redirects 후 렌더링 전에 실행됩니다.

자세한 내용은 미들웨어  설명서를 참조하세요.


6. 대규모 리디렉션 관리(고급)

많은 수의 리디렉션(1000개 이상)을 관리하려면 미들웨어를 사용하여 사용자 지정 솔루션을 만드는 것을 고려할 수 있습니다. 이렇게 하면, 애플리케이션을 다시 배포할 필요 없이 프로그래밍 방식으로 리디렉션을 처리할 수 있습니다.

이렇게 하려면 다음 사항을 고려해야 합니다:

  1. 리디렉션 맵 생성 및 저장.
  2. 데이터 조회 성능 최적화.

Next.js 예제: 아래 권장 사항의 구현에 대한 예제는 Bloom 필터가 포함된 미들웨어 예제 를 참조하세요.


6.1 리디렉션 맵 생성 및 저장

리디렉션 맵은 데이터베이스(일반적으로 키-값 저장소) 또는 JSON 파일에 저장할 수 있는 리디렉션 목록입니다.

다음 데이터 구조를 고려하세요:

json
1
{
2
"/old": {
3
"destination": "/new",
4
"permanent": true
5
},
6
"/blog/post-old": {
7
"destination": "/blog/post-new",
8
"permanent": true
9
}
10
}

미들웨어에서는, Vercel의 Edge Config 또는 Redis와 같은 데이터베이스에서 읽고 들어오는 요청에 따라 사용자를 리디렉션할 수 있습니다:

middleware.ts
1
import { NextResponse, NextRequest } from 'next/server'
2
import { get } from '@vercel/edge-config'
3
4
type RedirectEntry = {
5
destination: string
6
permanent: boolean
7
}
8
9
export async function middleware(request: NextRequest) {
10
const pathname = request.nextUrl.pathname
11
const redirectData = await get(pathname)
12
13
if (redirectData && typeof redirectData === 'string') {
14
const redirectEntry: RedirectEntry = JSON.parse(redirectData)
15
const statusCode = redirectEntry.permanent ? 308 : 307
16
return NextResponse.redirect(redirectEntry.destination, statusCode)
17
}
18
19
// No redirect found, continue without redirecting
20
return NextResponse.next()
21
}

6.2 데이터 조회 성능 최적화

들어오는 모든 요청에 대해 대규모 데이터 집합을 읽는 것은 느리고 비용이 많이 들 수 있습니다. 데이터 조회 성능을 최적화할 수 있는 두 가지 방법이 있습니다:

  • 빠른 읽기에 최적화된 데이터베이스(예: Vercel Edge Config 또는 Redis)를 사용합니다.
  • 블룸 필터와 같은 데이터 조회 전략을 사용하여 더 큰 리디렉션 파일이나 데이터베이스를 읽기 전에 리디렉션이 존재하는지 효율적으로 확인합니다.

앞의 예시를 고려하면 생성된 블룸 필터 파일을 미들웨어로 가져온 다음 들어오는 요청 경로명이 블룸 필터에 존재하는지 확인할 수 있습니다.

존재하는 경우 실제 파일을 확인하고 사용자를 적절한 URL로 리디렉션하는 라우트 핸들러 로 요청을 전달합니다. 이렇게 하면 모든 수신 요청의 속도를 저하시킬 수 있는 대용량 리디렉션 파일을 미들웨어로 가져오는 것을 방지할 수 있습니다.

middleware.ts
1
import { NextResponse, NextRequest } from 'next/server'
2
import { ScalableBloomFilter } from 'bloom-filters'
3
import GeneratedBloomFilter from './redirects/bloom-filter.json'
4
5
type RedirectEntry = {
6
destination: string
7
permanent: boolean
8
}
9
10
// Initialize bloom filter from a generated JSON file
11
const bloomFilter = ScalableBloomFilter.fromJSON(GeneratedBloomFilter as any)
12
13
export async function middleware(request: NextRequest) {
14
// Get the path for the incoming request
15
const pathname = request.nextUrl.pathname
16
17
// Check if the path is in the bloom filter
18
if (bloomFilter.has(pathname)) {
19
// Forward the pathname to the Route Handler
20
const api = new URL(
21
`/api/redirects?pathname=${encodeURIComponent(request.nextUrl.pathname)}`,
22
request.nextUrl.origin,
23
)
24
25
try {
26
// Fetch redirect data from the Route Handler
27
const redirectData = await fetch(api)
28
29
if (redirectData.ok) {
30
const redirectEntry: RedirectEntry | undefined = await redirectData.json()
31
32
if (redirectEntry) {
33
// Determine the status code
34
const statusCode = redirectEntry.permanent ? 308 : 307
35
36
// Redirect to the destination
37
return NextResponse.redirect(redirectEntry.destination, statusCode)
38
}
39
}
40
} catch (error) {
41
console.error(error)
42
}
43
}
44
45
// No redirect found, continue the request without redirecting
46
return NextResponse.next()
47
}

그런 다음 Route Handler에서:

app/redirects/route.ts
1
import { NextRequest, NextResponse } from 'next/server'
2
import redirects from '@/app/redirects/redirects.json'
3
4
type RedirectEntry = {
5
destination: string
6
permanent: boolean
7
}
8
9
export function GET(request: NextRequest) {
10
const pathname = request.nextUrl.searchParams.get('pathname')
11
if (!pathname) {
12
return new Response('Bad Request', { status: 400 })
13
}
14
15
// Get the redirect entry from the redirects.json file
16
const redirect = (redirects as Record<string, RedirectEntry>)[pathname]
17
18
// Account for bloom filter false positives
19
if (!redirect) {
20
return new Response('No redirect', { status: 400 })
21
}
22
23
// Return the redirect entry
24
return NextResponse.json(redirect)
25
}

알아두면 유용합니다:

  • bloom-filters를 생성하려면 블룸 필터와 같은 라이브러리를 사용할 수 있니다.
  • 악의적인 요청을 방지하기 위해 라우트 핸들러에 대한 요청의 유효성을 검사해야 합니다.