인프라/CI-CD

vue프로젝트를 nginx로 배포 시 router에 등록 된 주소를 직접 입력시 404에러가 발생하는 문제

2024. 2. 19. 00:24
글 목차


728x90

결론

이건 server-name 뒤에 어떤 uri가 들어와도 index.html을 실행해야 되는데 nginx가 그러지를 않고 해당 경로에 있을 없는 파일을 찾아대기 때문에 발생하는 문제이다.

 

예를 들어 example.com/about 이라는 주소가 router에 등록되어 있어 이를 그대로 쳐서 들어간다면

nginx은 root 디렉터리의 about.html를 찾게 된다는 점이다. 그런데 vue프로젝트는 index.html 밖에 생성하지 않는다. 그래서 404에러가 발생하는 것이다.

 

이를 해결하기 위해서는 어떤 주소로 들어오더라도 index.html을 일단 실행시키도록 해야 한다.

 

ec2에서 /etc/nginx/sites-available로 이동하자. (nginx 가 설치되어있다는 전제하)

 

그럼 https://okane-on-cliff.tistory.com/302 여기서 만들었던 conf 파일이 있다.

 

그 내용은 다음과 같다.

server {
        location /api {
                proxy_pass http://localhost:9999/api;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header Host $host;
        }
        location / {
                try_files $uri $uri /index.html; //바로 이부분
        }

        listen 443 ssl;
        ssl_certificate /etc/letsencrypt/live/mmmmmmmmm.org/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/mmmmmmmmmmm.org/privkey.pem;
}

server {
        if ($host = mmmmmmmmmmmm.org) {
                return 301 https://$host$request_uri;
        }

        listen 80;
        server_name mmmmmmmmmmmm.org;

        return 404;
}

 

중요한 부분은

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

 

이부분이다. 이 설정으로 인해 /api를 제외하고(먼저 써졌으니까) 나머지 uri가 server_name 뒤에 오더라도 먼저 index.html을 찾게 된다.

728x90
vue프로젝트를 nginx로 배포 시 router에 등록 된 주소를 직접 입력시 404에러가 발생하는 문제