๐ Rewrites์ Redirects ์์๋ณด๊ธฐ
๋ก์ปฌ์์ Next.js
๋ก ์์
ํ ๋ ํ ๊ฐ ํ๋ก์ ํธ๊ฐ ์๋๋ผ ๋ ๊ฐ ํ๋ก์ ํธ๋ฅผ ๋์์ ์คํํด์ผ ํ๋ ๊ฒฝ์ฐ๊ฐ ์ข
์ข
์๋ค. ์๋ฅผ ๋ค๋ฉด ๋ก๊ทธ์ธ์ ๋ด๋นํ๋ Aํ๋ก์ ํธ(port: 3001)์์ ๋ณธ์ธ์ธ์ฆ์ ๋ด๋นํ๋ Bํ๋ก์ ํธ(port: 3000)๋ฅผ ์คํํ๋ ๊ฒฝ์ฐ๊ฐ ๊ทธ๋ฐ ๊ฒฝ์ฐ๋ค. ์ด๋ด ๋ A์์ Bํ๋ก์ ํธ๋ก ๋์ด๊ฐ๋ ค๋ฉด http://localhost:3000/verifications
๋ฅผ ์์ฑํ๊ณ ๋ค์ B์์ Aํ๋ก์ ํธ๋ก ๋์ด์ฌ ๋๋ http://localhost:3001/auth-web
์ ์์ฑํ๊ณ AWS๋ฅผ ํตํด ๋ฐฐํฌ ํ ๋๋ path
๋ง ๋จ๊ฒจ๋๊ณ , ๋ก์ปฌ์์ ํ
์คํธ ํ ๋๋ ๋ค์ ํธ์คํธ์ ํฌํธ๋ฅผ ๋ถ์ด๊ณ .. ์ด๋ ๊ฒ ์๋์ ์ด๊ณ ๋ฒ๊ฑฐ๋ก์ด ์์
์ ์ง์ํ๋ค๊ฐ ๋ค๋ฅธ ์์
์ ํ์ง ๋ชปํ ๊ฒ ๊ฐ์๋ค.
์ด๋ด ๋ next.config.js
์์ ๊ด๋ จ ์ค์ ์ ํ ์ ์์๋๋ฐ, ๋ฐ๋ก Rewrites
์ Redirects
์ด๋ค.
Rewrites
์ Redirects
์ ๊ณตํต์ ์ธ ํน์ง์ ๋ค์ด์ค๋ ์์ฒญ(incoming request)๊ฒฝ๋ก๋ฅผ ๋ค๋ฅธ ๊ฒฝ๋ก(destination path)๋ก ๋งคํํด์ค๋ค. ๊ฒฐ์ ์ ์ธ ์ฐจ์ด๋ ๋ฐ๋ก ์ฌ์ฉ์๊ฐ ์์์ฐจ๋ฆด ์ ์๋๋์ธ๋ฐ, Rewrites
๋ destination path์ URL ํ๋ก์์ ๋ง์คํน์ผ๋ก ์ธํด ์ฌ์ฉ์์ ๋์ ๋ณํจ์ด ์๋(hasn't changed)๊ฒ์ฒ๋ผ ๋ณด์ด๊ณ , ๋ฐ๋๋ก Redirects
๋ ์ ํ์ด์ง๋ก ๋ผ์ฐํ
๋๊ณ URL ๋ณ๊ฒฝ์ฌํญ์ ๋ณด์ฌ์ฃผ๊ธฐ ๋๋ฌธ์ ์ฌ์ฉ์์ ์
์ฅ์์ ๋์ ๋ณํจ์ด ์๋ ๊ฒ์ฒ๋ผ ๋ณด์ธ๋ค.
Rewrites
์ Redirects
๋ชจ๋ next.config.js
์์ ์ค์ ํ ์ ์์ผ๋ฉฐ, ์์ ์ฝ๋๋ ๋ค์๊ณผ ๊ฐ๋ค. source
๋ incoming request path
์ฆ, ์์ฒญ์ด ๋ค์ด์จ ๊ฒฝ๋ก๋ฅผ ์๋ฏธํ๊ณ , destination
์ ๋ผ์ฐํ
ํ๊ณ ์ถ์ path
๋ฅผ ์๋ฏธํ๋ค.
Redirects
๋ Rewrites
์ ๋ค๋ฅด๊ฒ permanent
property๊ฐ ์๋๋ฐ, true
์ผ ๊ฒฝ์ฐ 308 ์ํ ์ฝ๋๋ฅผ ๋ณด๋ด์ฃผ๊ณ , false
์ผ ๊ฒฝ์ฐ์๋ 307 ์ํ์ฝ๋๋ฅผ ๋ณด๋ด์ค๋ค. ์ํ์ฝ๋ 308๊ณผ 307์ ์ฐจ์ด๋ redirect forever & cache
, redirect temporary & is not cached
์ ์ฐจ์ด์ธ๋ฐ, ์ ํต์ ์ผ๋ก temporary redirect
์ธ ๊ฒฝ์ฐ์๋ 302๋ฅผ, permanent redirect
์ธ ๊ฒฝ์ฐ 301์ ์ฌ์ฉํ์ผ๋, ๋ง์ ๋ธ๋ผ์ฐ์ ๋ค์ด original method
์ ๊ด๊ณ์์ด redirect
์ ์์ฒญ ๋ฐฉ๋ฒ์ GET
์ผ๋ก ์ฌ์ฉํ๋ค. ์๋ฅผ ๋ค์ด, ๋ธ๋ผ์ฐ์ ๊ฐ /v2/users
์์น์ ์๋ 302 ์ฝ๋์ ํจ๊ป POST /v1/users
์์ฒญ์ ํ๋ ๊ฒฝ์ฐ, POST /v2/users
์์ฒญ์ ์์ํ ์ ์์ง๋ง ๊ทธ ๋์ GET /v2/users
๋ฅผ ์์ฒญํ ์ ์๋ค. ๊ทธ๋์ Next.js
๋ 307
, 308
์ํ ์ฝ๋๋ก ์์ฒญ์ ๋ช
์์ ์ผ๋ก ๋ณด์กดํ๊ธฐ ์ํด ์ฌ์ฉํ๋ค.
// next.config.js
// Rewrites
module.exports = {
async rewrites() {
return [
{
source: '/about',
destination: '/',
},
]
},
}
// Redirects
module.exports = {
async redirects() {
return [
{
source: '/about',
destination: '/',
permanent: true,
},
]
},
}
์์ฑํ๋ ๋ด์ฉ์ ํ ๋๋ก ์๋ก ์์ ์ธ๊ธํ๋ A์์ Bํ๋ก์ ํธ๋ก ๋์ด๊ฐ ๋์ Rewrites
์ B์์ Aํ๋ก์ ํธ๋ก ๋์ด๊ฐ ๋ Rewrites
๋ฅผ ์์ฑํ๋ฉด ๋ค์๊ณผ ๊ฐ๋ค.
// A(3001) -> B(3000)
const nextConfig = {
async rewrites() {
return [
{
source: '/verifications/:path*',
destination: `http://localhost:${B_PORT}/verifications/:path*`,
basePath: false,
},
]
}
}
// B(3000) -> A(3001)
const nextConfig = {
async rewrites() {
return [
{
source: '/auth-web/:path*',
destination: `http://localhost:${A_PORT}/auth-web/:path*`,
basePath: false,
},
]
}
}
โ Reference
๋๊ธ