SERVER
[nginx] nginx.conf 백앤드 연동(proxy 설정 방법)
amoomar
2025. 4. 21. 15:53
반응형
해당 포스팅에서는 nginx에서 proxy설정을 통해 백엔드 프로젝트 및 api 모듈과 연결하는 방법에 대해 기재해보았다.
목차
GET/POST 요청 허용처리(nginx.conf)
server 내부에 '/'에 대한 로케이션 블럭 내용이다.
location / {
try_files $uri $uri/ /index.html;
#nginx 정적 소스에서 POST 요청 안하는게 기본값. GET, POST 요청만 허용하겠다 명시화.
limit_except GET POST {
deny all;
}
}
해당 블럭을 통해 기대되는 기능은 아래와 같다.
- 요청된 경로가 파일인지 확인 → 없으면 index.html로 리다이렉트 (SPA 지원용)
- GET과 POST는 허용
- 그 외 요청 메서드는 모두 차단 (보안 목적)
PROXY 설정(nginx.conf)
server 내부에 '/chem_acc_impact'혹은 ' /chem_acc_impact/* ' 요청에 대한 로케이션 블럭 내용이다.
해당 코드를 활용하여 'proxy_pass'로 GET/POST/OPTIONS요청을 송신할 수 있게 된다.
location /chem_acc_impact {
proxy_pass http://API서버IP:포트번호;
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;
add_header 'Access-Control-Allow-Origin' 'http://해당 웹 애플리케이션 서버 IP:포트번호' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'http://해당 웹 애플리케이션 서버 IP:포트번호' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
}
해당 블럭을 통해 기대되는 기능은 아래와 같다.
/chem_acc_impact | 이 경로로 들어온 요청을 프록시 처리 |
proxy_pass | 요청을 백엔드 API로 전달 |
proxy_set_header | 클라이언트 정보 전달 |
add_header ... | CORS 허용 설정 (다른 출처에서의 요청 허용) |
if ($request_method = 'OPTIONS') | 사전 요청(preflight)에 대해 204 응답으로 허용 |
Spring프로젝트 CORS 필터(백앤드)
해당 설정이 필요한 이유를 간단하게 정리해보면 아래와 같다.
WebMvcConfig
package com.example.dna1;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**") //혹은 '/chem_acc_impact/**'와 같이 허용할 요청을 작성
.allowedOrigins("http://localhost:3000") //웹 애플리케이션 접속 url
.allowedMethods("GET", "POST", "OPTIONS")
.allowedHeaders("DNT", "User-Agent", "X-Requested-With", "If-Modified-Since", "Cache-Control", "Content-Type", "Range")
.exposedHeaders("Content-Length", "Content-Range")
.allowCredentials(true)
.maxAge(3600);
}
}
Spring Security 사용중이라면?
@EnableWebSecurity
@Configuration
위 어노테이션을 활용한 클래스를 선언하여 스프링 암호화를 설정한 상태라면, WebMvcConfig가 아니라, 해당 java 클래스에 아래 CORS 설정을 적용해주어야한다.
//운영서버 CORS 설정
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.addAllowedOrigin("http://localhost:3000"); //웹 애플리케이션 url
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", configuration);
return source;
}
필요한 설정들을 모두 마치게 되면 PROXY 설정이 완료된다.
반응형