💡 TIL 20230816 - redirect와 rewrite
1. redirect, rewrite의 공통점/차이점
redirect와 rewrite
유저가 어떤 path로 접근하는 경우, 다른 path나 경로로 자동으로 이동시켜주는 기능이다.
공통점
- next.js에서 기본적으로 제공하는 기능이다.
- 두 가지 모두 유저가 특정 path로 이동 시 의도한 path로 이동시키 위해 사용한다.
차이점
- redirect는 정해진 path로 url이 변경되어 유저가 확인할 수 있다.
- 반면 rewrite는 redirect 해주는 것은 똑같지만, 유저가 처음 입력한 url 그대로 유저에게 보여진다.
2. redirect, rewrite 설정 방법
1) next.config.js
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/about',
destination: '/',
permanent: false,
},
{
source: '/mypage',
destination: '/myprofile',
permanent: true,
},
]
},
async rewrites() {
return [
{
source: '/about',
destination: '/',
},
]
}
}
기본 url이 `localhost:3000`이라고 가정했을 경우, 위의 redirects 설정은 사용자가 `localhost:3000/about`으로 접근 시 다시 기본 `/` (=`localhost:3000`)으로 redirect 시켜준다는 의미이다.
- source : 사용자가 요청하는 path의 패턴을 말한다.
- destination : 개발자가 의도해서 리다이렉트 시키기 위한 목적지 path를 의미한다.
- // redirect
- permanent : true or false - 이 리디렉션이 영구한지 아닌지에 따라 브라우저나 검색엔진이 이 정보를 기억하는지 여부가 결정된다.
3. source, destination 설정
1) 외부 웹사이트로 리디렉션
destination의 path는 현재 웹페이지 내의 path로만 설정할 수 있는 것이 아니고, 외부 웹사이트로도 설정이 가능하다.
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/about',
destination: 'https://google.com',
permanent: true,
},
]
},
}
위처럼 설정해주면, 유저가 `localhost:3000/about`으로 접근 시 google.com으로 이동한다.
2) pattern matching
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/old-blog/:id',
destination: '/new-blog/:id',
permanent: true,
},
]
},
}
위처럼 설정해주면, 유저가 `localhost:3000/old-blog/124211`로 접근 시, `localhost:3000/new-blog/124211`로 이동한다.
124211 자리에 다른 id값 오더라도 똑같이 작동한다.
3) catch
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/old-blog/:id*',
destination: '/new-blog/:id*',
permanent: true,
},
]
},
}
위처럼 설정해주면, 유저가 `localhost:3000/old-blog/124211/comments/49285`로 접근 시, `localhost:3000/new-blog/124211/comments/49285`를 목적지로 리디렉션 해준다.
3. rewrite를 이용한 api key 숨기기
// next.config.js
/** @type {import('next').NextConfig} */
const API_KEY = process.env.API_KEY;
const nextConfig = {
reactStrictMode: true,
async rewrites() {
return [
{
source: "/api/movies",
destination: `https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}`
},
]
}
}
module.exports = nextConfig
.env
API_KEY=본인의 API키
- 위와 같이 기본 next.config 파일에서의 rewrite 설정을 통해 API_KEY를 손쉽게 숨길 수 있다.
참고 사이트
'✍️ What I Learned > TIL' 카테고리의 다른 글
[TIL] Next.js 13 - getStaticProps, getStaticPaths (feat. 12버전에서의 getServerSideProps) (0) | 2023.08.18 |
---|---|
[TIL] Next.js - SSR vs SSG vs ISR (0) | 2023.08.17 |
[TIL] React.js와 Next.js의 차이점 - Library vs Framework, CSR vs SSR (0) | 2023.08.15 |
[TIL] npm vs npx vs yarn (0) | 2023.08.15 |
[TIL] 간단한 Recoil 첫 사용기 (0) | 2023.08.14 |