카테고리 없음

[Nginx] 페이지 새로고침 시 404 Not Found error

날라루 2024. 1. 18. 17:57

Vue 애플리케이션을 nginx 웹서버에 올려 생성한 docker 이미지를 배포했더니, 새로고침을 했을 때 nignx에서 404 Not Found 페이지를 반환하였다.

Nginx config

nginx의 default config를 살펴보면 다음과 같은 설정이 있다.

  location / {
      ...
      try_files $uri $uri/ =404;
  }

'https://example.com/something '으로 요청을 보내면, nginx는 root 디렉토리에서 something.html 파일을 찾는다. 없으면 404error를 반환한다. Vue와 같은 SPA에서는 해당 파일이 존재하지 않으므로 404 Not Found 페이지를 반환하는 것이다.

해결방법

프로젝트 하위에 새로운 nginx.conf를 만들고 Dockerfile에 nginx config파일을 새 파일로 교체하는 명령어를 추가한다.

nginx.conf
server {
  listen 80;

  location / {
      alias /usr/share/nginx/html/;
      try_files $uri $uri/ /index.html;
  }
}

Dockerfile

FROM node:18-alpine as build-stage 
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . ./
RUN npm run build

FROM nginx:stable-alpine as production-stage
RUN rm /etc/nginx/conf.d/default.conf
COPY ./nginx/nginx.conf /etc/nginx/conf.d/nginx.conf
COPY --from=build-stage /app/dist/spa /usr/share/nginx/html
EXPOSE 80 

CMD ["nginx", "-g","daemon off;"]