Nginx 새로고침 시 동적 라우팅 안되는 문제

junto·2024년 6월 16일
0

devops

목록 보기
8/9
post-thumbnail

TLDR

  • 동적 페이지에 클릭해서 접근하면 문제가 없지만 동적 페이지에서 새로고침을 할 경우 Nginx의 403 에러페이지가 뜬다.
    • Nginx 403 error: directory index of [folder] is forbidden
  • 이번에 Nginx 설정을 새로 추가하면서 생긴 문제였다. 아래와 같이 설정하면 간단히 해결할 수 있다.
location / {
    try_files $uri $uri.html /index.html;
}
  • $uri.html이 없으면 새로고침할 때 제대로 페이지를 찾지 못한다.

Nginx 기본 설정

location, root, index

location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
}
  • location / 해당 url 경로(/) 에 대한 처리 방법을 정의하겠다는 것을 말한다.
  • root 웹 서버가 찾을 디렉토리의 기본 경로를 말한다.
  • index 지시어는 기본적으로 제공할 파일을 지정한다. 즉, /usr/share/nginx/html/index.html 파일을 먼저 찾고 없으면 /usr/share/nginx/html/index.htm 파일을 찾아서 제공한다.

try_files

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

try_files 동작 과정

  • try_files는 첫 번째 $uri를 통해 $uri라는 파일을 찾는다. 두 번째로 $uri/ 를 통해 $uri가 디렉토리 이름일 수도 있다고 가정하고 디렉토리를 찾는다. 해당 디렉토리 안에 $uri라는 파일이 있다면 이를 제공한다. 만약에 이런 과정을 거쳐 매칭되지 않았다면 고정된 경로에 있는 /index.html 파일을 보여준다.
/usr/share/nginx/html; 
				 ├── index.html
         ├── a
         │   └── index.html
  • $uri가 a라고 했을 때, $uri라는 파일이 없으므로 $uri/ 를 통해 디렉토리를 검사한다. 디렉토리에 찾으려는 index인 index.html 파일이 있으므로 이를 보여준다. 해당 동작을 네트워크 탭으로 보면 아래와 같다.

문제가 생긴 Nginx 요청 분석하기

1. 배송조회 클릭해서 들어간 경우 (mypage/purchased)

119.192.96.3 - - [15/Jun/2024:23:24:27 +0000] "GET /api/orders?page=0&size=5 HTTP/1.1" 200 2856 "https://ggorangjirang.duckdns.org/mypage/purchased" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36" "-"
119.192.96.3 - - [15/Jun/2024:23:24:27 +0000] "GET /api/orders?page=0&size=5 HTTP/1.1" 200 2856 "https://ggorangjirang.duckdns.org/mypage/purchased" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36" "-"

2. 배송조회에서 새로고침한 경우 (mypage/purchased)

119.192.96.3 - - [15/Jun/2024:23:25:32 +0000] "GET /mypage/purchased HTTP/1.1" 301 169 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36" "-"
2024/06/15 23:25:32 [error] 6#6: *16583 directory index of "/home/html/mypage/purchased/" is forbidden, client: 119.192.96.3, server: [ggorangjirang.duckdns.org](http://ggorangjirang.duckdns.org/), request: "GET /mypage/purchased/ HTTP/1.1", host: "[ggorangjirang.duckdns.org](http://ggorangjirang.duckdns.org/)"
  • 문제가 생긴 이유는 $uri/ 설정 때문이었다. next.js가 해당 페이지를 동적으로 만듦에도 요청 uri에 대한 존재하지 않는 디렉토리를 찾으면서 403에러가 발생한 것이다.

  • Nginx 403 error: directory index of [folder] is forbidden

  • 분명 동적 페이지임에도 동적 페이지 경로를 정적 파일 경로에서 Nginx가 찾고 있었다! index.html을 찾으면 되는 데 동적 페이지 경로에서 정적 파일을 찾고 있었다. 디렉토리 설정을 지워주고, html파일을 찾으려는 설정으로 변경해 주면, 정상적으로 동작한다.

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

참고자료

profile
꾸준하게

0개의 댓글

관련 채용 정보