Nginx 프록시 설정

싱판다·2023년 8월 20일

api 요청 시 cors 문제를 해결하기 위해 proxy_pass 를 설정했는데, 다음 설정이 효과를 보아 작성한다.

default.conf 파일에 다음과 같이 작성해 api를 호출할 수 있었다.
다음은 /api 경로로 접근 시, http://project.test.co.kr:8080로 변경되어 요청을 전달한다.


    location /api {
   
		# Check if the origin of th request
		set $cors '';

		if ($http_origin ~* ((http|https)?://project1\.test\.co\.kr?(:[0-9]+)?$)) {
			set $cors 'on';
		}

		if ($request_method = OPTIONS) {
			set $cors "${cors}_options";
		}

		# Allow CORS on preflight request
		if ($cors = 'on_options') {
			add_header 'Content-Length' 0;
			add_header 'Content-Type' 'text/plain; charset=utf-8';
			add_header 'Access-Control-Allow-Origin' "$http_origin";
			add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTIONS';
			add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept';
			return 204;
		}

		# Proxy pass to upstream
		rewrite ^/api(.*)$ $1?$args break;
		proxy_pass http://project.test.co.kr:8080;
		proxy_redirect     off;
		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-Host $server_name;

		# Allow CORS on other requests after returning from the upstreams
		if ($cors = 'on') {
			add_header 'Access-Control-Allow-Origin' "$http_origin";
			add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTIONS';
			add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept';
		}
	}
profile
뭐든 많이 배우고 싶다

0개의 댓글