Choorai
| 문서
배포 후 자주 발생

SPA 404 에러 해결하기

React/Vue 앱 배포 후 새로고침하면 404가 뜨나요? SPA(Single Page Application)의 라우팅 설정 문제입니다.

TL;DR (핵심 요약)

모든 경로를 index.html로 리다이렉트하도록 설정하세요. 호스팅 서비스마다 설정 방법이 다릅니다.

심각

404 Page Not Found

원인

SPA는 클라이언트 사이드 라우팅을 사용합니다. 서버는 /about, /dashboard 같은 경로를 모르기 때문에 404를 반환합니다.

해결책
  1. 호스팅 서비스 설정에서 모든 경로를 index.html로 리다이렉트
  2. Cloudflare Pages: _redirects 파일 생성
  3. Vercel: vercel.json rewrites 설정
  4. Nginx: try_files 설정

호스팅별 해결 방법

Cloudflare Cloudflare Pages

프로젝트 루트 또는 public 폴더에 _redirects 파일을 생성하세요.

public/_redirects
/* /index.html 200

Vercel

vercel.json
{
  "rewrites": [
    { "source": "/(.*)", "destination": "/index.html" }
  ]
}

Netlify

public/_redirects
/*    /index.html   200

또는 netlify.toml 파일:

netlify.toml
[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

Nginx

nginx.conf
server {
    listen 80;
    server_name your-domain.com;
    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

왜 이런 문제가 발생하나요?

SPA는 JavaScript가 브라우저에서 URL을 처리합니다. 하지만 새로고침하면 브라우저가 서버에 해당 경로를 요청하고, 서버는 그 경로에 실제 파일이 없으니 404를 반환합니다. 해결책은 모든 요청을 index.html로 보내서 JS가 라우팅을 처리하게 하는 것입니다.

관련 문서