Nginx 라우팅 시 request의 host 이름이 localhost가 될 때

조예진·2021년 10월 25일
0
post-thumbnail

문제 상황

사전 설명

  • Django 프로젝트 이미지를 빌드한 Docker 컨테이너를 8000번 포트에 띄움
  • Nginx로 api.domain.com 으로 들어오는 요청을 localhost:8000 으로 라우팅
  • Django 프로젝트에서는 회원가입에 성공하면 입력된 이메일로 인증 메일을 발송하고 있음

문제 발생

  • 배포된 서버인데도 인증 링크의 도메인 부분이 localhost:8000으로 표시된다...

해결

원인

def build_absolute_uri(request, location, protocol=None):
    """request.build_absolute_uri() helper

    Like request.build_absolute_uri, but gracefully handling
    the case where request is None.
    """
    from .account import app_settings as account_settings

    if request is None:
        site = Site.objects.get_current()
        bits = urlsplit(location)
        if not (bits.scheme and bits.netloc):
            uri = '{proto}://{domain}{url}'.format(
                proto=account_settings.DEFAULT_HTTP_PROTOCOL,
                domain=site.domain,
                url=location)
        else:
            uri = location
    else:
        uri = request.build_absolute_uri(location)
   	(...)

위 코드는 allauth 패키지의 utils 코드 일부인데, 인증 링크의 도메인 부분을 생성하는 코드이다. 이 함수를 실행할 때 request 객체가 전달된다면 request.build_absolute_uri를 실행하여 도메인 주소를 얻는데, 이는 request 객체가 가지고 있는 uri 주소를 기반으로 절대 URI를 가져오는 것이다. 참고 - 공식 문서
그런데 앞서 Nginx 서버 라우팅으로 인해 api.domain.com에서 localhost:8000으로 호스트 네임이 변경되었다. 즉 request가 가지고 있는 도메인 주소는 localhost:8000이다.

해결 방법

Nginx의 default.conf 파일에서 api.domain.com을 라우팅하는 부분에 header를 설정해 주는 부분을 추가해야한다.

  1. proxy_set_header Host $http_host;를 추가한다.
server {
        listen 80;
        listen [::]:80;
        server_name api.domain.com;
        location / {
                proxy_pass http://localhost:8000;
                proxy_set_header Host $http_host;
        }
}
  1. 저장 후 sudo systemctl restart nginx 커맨드로 Nginx를 다시 실행한다.
profile
https://oooooroblog.com 으로 이사갔어요

0개의 댓글