Nginx

nginx 로 proxy 연결시 실제 아이피, 프로토콜 확인하기

빠빠담 2020. 4. 19. 23:51
반응형

https://lovedove.tistory.com/107

 

nginx 로 proxy 연결시 실제 아이피, 프로토콜 확인하기

node.js + express 를 사용하여 서비스 구성. 앞단에 nginx 를 두고 proxy로 사용하고 있음 문제1. node.js 에서 아이피 확인 - node.js 에서 req.connection.remoteAddress 로 접근 아이피를 확인 - node.js 로..

lovedove.tistory.com

 

node.js + express 를 사용하여 서비스 구성.

앞단에 nginx 를 두고 proxy로 사용하고 있음

 

 

문제1. node.js 에서 아이피 확인

 - node.js 에서 req.connection.remoteAddress 로 접근 아이피를 확인

 

 - node.js 로 바로 접근시는 정상적으로 아이피 확인

 

 - nginx 를 거치면 127.0.0.1 로 나옴

 

 - nginx proxy 설정에서 proxy_pass http://127.0.0.1:3000/; 으로 되어 있어서....

 

 

 

문제2. node.js 에서 http, https 구분

 -  로그인 페이지 구축을 위해서...

 

 - http 로 페이지 접근시 https 로 리다이렉트 되도록 개발을 하려 함

 

 - http와 https 접근을 구분하기 위해 node.js 에서 req.protocol 값을 가져옴.

 

 - https 접근일 때에도 node.js 에서는 http  로 결과 출력

 

 - nginx proxy 설정에서 proxy_pass http://127.0.0.1:3000/; 으로 되어 있어서....

 

 

해결 방법.

 - nginx conf 에서 proxy_set_header 를 사용하여 헤더에 값 설정 후 node.js 에서 해당하는 값을 읽어와서 처리

 

 nginx.conf 에 proxy_set_header 항목 추가

    location / {

      proxy_set_header X-Real-IP $remote_addr;

      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;       # 포워딩 아이피

      proxy_set_header Host $http_host;

      proxy_set_header X-Forwarded-Proto $scheme;                                  # 프로토콜

      proxy_set_header X-NginX-Proxy true;

      proxy_buffering off;

      proxy_pass http://127.0.0.1:8888/;

      client_max_body_size 200M;

      proxy_redirect off;

    }

 

 

node.js 에서 아래와 같은 방식으로 값을 가져 온다.

 

 -  ip 가져오기

var ip_address = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

 

 

 - 프로토콜 가져오기

var protocol = req.headers['x-forwarded-proto'] || 'http';

 

반응형