본문 바로가기

프로그래밍 TIP/기타

Nginx Node.js React 환경에서 Socket.io 404 오류 수정

http에서 잘 동작하던 socket.io가 ssl 인증서 설정 후 동작하지 않는다.

포트는  4000번 사용한다고 가정한다.

useEffect(() => {
    const socket = io('https://abc.test.com')
    ....
},[])

예를 들어 도메인이 abc.test.com 이라면

http://localhost:4000 -> 동작안함 

http://localhost:4000 -> 동작안함 

ws://localhost:4000 -> 동작안함

wss://localhost:4000 -> 동작안함

http://abc.test.com -> 동작안함

https://abc.test.com -> 동작안함 

https://abc.test.com:4000 -> 동작안함 

뭐가 문제인지 찾던 도중 nginx에 추가로 설정이 필요하다는 것을 알게 됐다.

아래와 같이 nginx 설정을 추가하면 정상적으로 동작한다.

server {
    server_name abc.test.com;

    location /socket.io/ {
        proxy_pass http://localhost:4000/socket.io/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    ...
}