/ NEXTJS

(NextJS) redirect와 rewrite

NextJS는 다음과 같이 구성되어 있습니다.

오늘은 NextJS의 redirect와 rewrites 사용법에 대해 알아보겠습니다.

redirect

// next.config.js에 작성합니다.

/** @type {import('next').NextConfig} */

const nextConfig = {
  reactStrictMode: true,
  async redirects() {
    return [
      {
        source : "/before",
        destination : "/after",
        permanent : false
      }
    ]
  }
}

module.exports = nextConfig

위와 같이 사용하면되는데, async redirects로 설정해주어 사용하면됩니다. source부분은 url로 먼저 접근하는 주소이고 destination은 source로 접근할 경우 변경될 주소입니다.

/before로 접근하면 /after가 되는 것이죠.

추가적인 redirect설정을 하고 싶다면 저 묶음을 배열에 추가해주면 됩니다.

  • 참고
    ex) /before/:path => /after/:path (:path부분은 기존과 동일한 값으로 유지)
    ex) /before/:path* => /after/:path* (*를 붙여주는 경우 어떤값이 오더라도 뒷부분 모두를 반영)

rewrites

const nextConfig = {
  reactStrictMode: true,
  async rewrites() {
    return [
      {
        source : "/api/movies",
        destination : `https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}`,
      }
    ]
  }
}

rewrites는 redirect와 같은 level에 추가하면되고 source값으로 불러오면 내부적으로 destination값을 호출하게됩니다. 예를 들어, api-key와 같이 숨기고 싶은 값이 url에 있을 경우 실제 url을 숨기고 다른 url로 대체할 수 있습니다.

End.