증상

 

404 Not Found

Vue.js를 사용한 웹 애플리케이션 개발 중 새로고침 시 404 페이지로 리다이렉트 되는 이슈가 발생하였다.

 

원인

 

해당 이슈는 SPA 앱을 개발할 때 발생하는 이슈로 connect-history-api-fallback 현상이라 한다.

Vue.js의 경우 라우터에 등록된 Vue 컴퍼넌트들을 모듈 번들러를 통하여 Javascript로 컴파일하여 WebServer의 Document Root 폴더에 가지고 있다. 

라우터를 이용한 정상적인 페이지 요청 시에는 해당 페이지에 맞는 js 파일을 클라이언트가 요청하지만, 새로고침 시에는 도메인과 라우터 Path를 가지고 WebServer에 존재하지 않는 요청을 보내기 때문에 발생하는 이슈이다.

 

해결방법

라이브러리를 사용하는 방법도 있지만, 공식 문서에 나와있는 서버 설정방법을 사용하여 해결하였다.

https://router.vuejs.org/guide/essentials/history-mode.html

 

Different History modes | Vue Router

Different History modes The history option when creating the router instance allows us to choose among different history modes. Hash Mode The hash history mode is created with createWebHashHistory(): import { createRouter, createWebHashHistory } from 'vue-

router.vuejs.org

 

해당 방법은 WebServer에 Http 요청이 들어왔을 때, 해당 요청을 rewrite 하는 방법이다.

 

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

 

서버 설정 문법은 아파치 레퍼런스 문서를 참고하면 된다.

https://httpd.apache.org/docs/current/rewrite/flags.html

 

RewriteRule Flags - Apache HTTP Server Version 2.4

RewriteRule Flags This document discusses the flags which are available to the RewriteRule directive, providing detailed explanations and examples. A RewriteRule can have its behavior modified by one or more flags. Flags are included in square brackets at

httpd.apache.org

위 설정문을 예시로 번역하면

RewriteRule ^index\.html$ - [L]

^index\.html$ 는 정규표현식으로 

index로 시작하며(^ 접두사)  (특수문자 .) html 로 끝나지 않는($ 접미사) 요청들이 다시 쓰는 대상이며

[L] 플래그는 조건의 끝을 의미한다.

Rewirte Cond 문장의 ! -f, ! -d는 파일과 디렉토리를 의미한다.

 

결론적으로 SPA 애플리케이션의 초기진입 페이지인 index.html이 아닌 URL로 들어오는 요청들을 index.html로 다시 보내는 설정이다.

위와같은 설정을 웹서버에 적용하여, Vue.js의 새로고침 시 404 페이지 리다이렉트 이슈를 해결할 수 있다.

 

참고자료

 

https://stackoverflow.com/questions/36399319/vue-router-return-404-when-revisit-to-the-url

 

Vue Router return 404 when revisit to the url

I just enable Vue router history mode. And it work fine when I visit to vue routing via v-href or href. But, when I try to refresh that page or go directly from browser address bar, it just return ...

stackoverflow.com

 

 

+ Recent posts