2026년 상식닷컴 선정 식당 & 카페 리스트
최근에 오픈한 호텔을 찾는다면 살펴보세요

웹서버구축 시 CORS 설정 방법은 무엇인가요?

_____
FAQ: 웹서버 구축 시 CORS 설정 방법

1. 질문: CORS란 무엇이며 왜 필요한가요?
답변:
- CORS(Cross-Origin Resource Sharing)는 도메인, 프로토콜, 포트가 다른 출처 간에 자원을 안전하게 공유하기 위한 표준입니다.
- 브라우저는 보안 정책(Same-Origin Policy)에 따라 다른 출처의 API 호출을 기본 차단하므로, CORS 헤더를 통해 허용된 출처만 요청을 수행하도록 합니다.

2. 질문: CORS 동작 원리는 어떻게 되나요?
답변:
- 브라우저가 리소스를 요청할 때 서버는 응답 헤더에 Access-Control-Allow-Origin, Access-Control-Allow-Methods 등을 포함해 허용 범위를 알립니다.
- 단순 요청(Simple Request)과 사전 요청(Preflight Request)이 있으며, Preflight는 OPTIONS 메서드를 사용해 허용 여부를 먼저 확인합니다.

3. 질문: 기본 CORS 관련 헤더는 어떤 것들이 있나요?
답변:
1) Access-Control-Allow-Origin: 허용할 출처(예: https://example.com 또는 *)
2) Access-Control-Allow-Methods: 허용할 HTTP 메서드(예: GET, POST, PUT)
3) Access-Control-Allow-Headers: 허용할 요청 헤더(예: Content-Type, Authorization)
4) Access-Control-Allow-Credentials: 쿠키·인증정보 허용 여부(true/false)
5) Access-Control-Expose-Headers: 클라이언트에서 접근 가능한 응답 헤더
6) Access-Control-Max-Age: Preflight 결과 유효 시간(초)

4. 질문: Apache(HTTPD)에서 CORS 설정은 어떻게 하나요?
답변:
- mod_headers 모듈 로드 확인:
LoadModule headers_module modules/mod_headers.so
- 가상호스트 또는 .htaccess에 다음 추가:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "GET,POST,OPTIONS,PUT,DELETE"
Header always set Access-Control-Allow-Headers "Content-Type, Authorization"

- OPTIONS 메서드를 처리하기 위해 필요 시 RewriteRule 또는 Allow from all 설정 추가.

5. 질문: Nginx에서 CORS 설정은 어떻게 하나요?
답변:
server {
listen 80;
server_name api.example.com;
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, DELETE";
add_header Access-Control-Allow-Headers "Authorization, Content-Type";
add_header Access-Control-Max-Age 1728000;
return 204;
}
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, DELETE";
add_header Access-Control-Allow-Headers "Authorization, Content-Type";
proxy_pass http://backend;
}
}

6. 질문: Node.js(Express)에서 CORS 설정은 어떻게 하나요?
답변:
- cors 패키지 설치: npm install cors
- 사용 예:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: ['https://example.com'],
methods: ['GET','POST','PUT','DELETE'],
credentials: true
}));
app.listen(3000);

7. 질문: Spring Boot에서 CORS 설정 방법은?
답변:
1) 전역 설정(Java Config)
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/ ")
.allowedOrigins("https://example.com")
.allowedMethods("GET","POST","PUT","DELETE")
.allowedHeaders("Content-Type","Authorization")
.allowCredentials(true)
.maxAge(3600);
}
}
2) 컨트롤러별 설정
@CrossOrigin(origins="https://example.com", methods={RequestMethod.GET,RequestMethod.POST})

8. 질문: Flask에서 CORS 설정은 어떻게 하나요?
답변:
- flask-cors 패키지 설치: pip install flask-cors
- 사용 예:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "https://example.com"}}, supports_credentials=True)
@app.route('/api/data')
def data():
return {'msg':'hello'}

9. 질문: Django에서 CORS 설정은 어떻게 하나요?
답변:
- django-cors-headers 설치: pip install django-cors-headers
- settings.py 수정:
INSTALLED_APPS += ['corsheaders']
MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware'] + MIDDLEWARE
CORS_ALLOWED_ORIGINS = [
"https://example.com",
"https://sub.example.com",
]
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = ['content-type','authorization']

10. 질문: credentials(쿠키/인증 정보)를 포함해 요청하려면?
답변:
- 서버: Access-Control-Allow-Credentials: true 헤더 추가
- 브라우저(클라이언트): fetch나 XHR 요청 시 credentials: 'include' 또는 withCredentials: true 설정
- Access-Control-Allow-Origin에 와일드카드(*)와 allow-credentials: true를 함께 사용할 수 없으므로, 명시적 도메인을 설정해야 합니다.

11. 질문: Preflight 요청을 처리할 때 주의사항은?
답변:
- OPTIONS 메서드를 204 또는 200으로 응답해야 하며, 모든 CORS 관련 헤더를 포함해야 합니다.
- Access-Control-Max-Age를 적절히 설정해 Preflight 호출 빈도를 줄일 수 있습니다.
- 프록시나 리버스 프록시 환경에서도 OPTIONS가 백엔드로 전달되도록 설정해야 합니다.

12. 질문: CORS 설정 후에도 동작하지 않을 때 어떻게 디버깅하나요?
답변:
- 브라우저 개발자 도구 Network 탭에서 요청/응답 헤더 확인
- 서버 로그(OPTIONS 포함) 확인
- 프록시·로드밸런서 등 중간 장치에서 헤더가 삭제되지 않는지 점검
- 브라우저 캐시나 확장 프로그램(Ad-block, 보안 플러그인) 비활성화 후 재시도

위 FAQ를 참고하여 웹서버 환경에 맞게 CORS 헤더를 정확히 설정하면 다른 출처 간 안전한 자원 공유가 가능합니다.
CORS(Cross-Origin Resource Sharing)는 도메인, 프로토콜, 포트가 서로 다른 출처 간에 브라우저가 안전하게 자원을 공유하도록 허용하는 메커니즘입니다.

웹 서버를 구축할 때 CORS를 올바르게 설정하지 않으면 클라이언트(예: React, Angular, Vue 등)에서 API 호출 시 보안 정책에 의해 요청이 차단될 수 있습니다.

다음은 주요 웹 서버 및 프레임워크별로 CORS를 설정하는 방법을 자세히 설명한 내용입니다.

1. CORS 기본 헤더 이해하기 - Access-Control-Allow-Origin: 허용할 출처(origin)를 지정합니다.

“*”로 설정하면 모든 출처를 허용하지만, 보안상 민감한 API에 대해서는 구체적인 도메인을 명시하는 것이 좋습니다.

- Access-Control-Allow-Methods: 허용할 HTTP 메서드(GET, POST, PUT, DELETE 등)를 쉼표로 구분하여 명시합니다.

- Access-Control-Allow-Headers: 클라이언트가 요청 시 사용할 수 있는 커스텀 헤더(예: Content-Type, Authorization 등)를 나열합니다.

- Access-Control-Allow-Credentials: 쿠키, 인증정보를 포함한 요청을 허용할지 여부를 true/false로 설정합니다.

- Access-Control-Max-Age: preflight 요청(OPTIONS)에 대한 캐시 유효 기간(초)을 지정합니다.



2. Apache HTTP Server에서 CORS 설정하기 1) 모듈 활성화 - httpd.conf 혹은 apache2.conf에 `mod_headers` 모듈이 로드되어 있는지 확인합니다.

``` LoadModule headers_module modules/mod_headers.so ```

2) 전역 또는 디렉토리별 설정 - 전역 설정 예시 (httpd.conf 안 VirtualHost 내에): ``` ServerName api.example.com Header always set Access-Control-Allow-Origin "https://frontend.example.com" Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" Header always set Access-Control-Allow-Headers "Content-Type, Authorization" Header always set Access-Control-Allow-Credentials "true" Preflight(OPTIONS) 요청은 204로 응답 RewriteEngine On RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=204,L] ``` - .htaccess 파일을 사용하는 경우 `` 블록을 적용할 수도 있습니다.



3. Nginx에서 CORS 설정하기 - Nginx 설정 파일(nginx.conf 또는 sites-available 디렉토리 내 서버 블록)에 아래를 추가합니다.

``` server { listen 80; server_name api.example.com; location / { 기본 CORS 헤더 add_header 'Access-Control-Allow-Origin' 'https://frontend.example.com'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization'; add_header 'Access-Control-Allow-Credentials' 'true'; OPTIONS 요청 처리: 204 응답 if ($request_method = OPTIONS ) { add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=UTF-8'; add_header 'Content-Length' 0; return 204; } 실제 프록시 패스나 루트 설정 proxy_pass http://backend_upstream; } } ```

4. Node.js(Express)에서 CORS 설정하기 - npm으로 공식 cors 미들웨어를 설치: ``` npm install cors ``` - 서버 코드에 적용: ```javascript const express = require('express'); const cors = require('cors'); const app = express(); // 단일 도메인 허용 app.use(cors({ origin: 'https://frontend.example.com', methods: ['GET','POST','PUT','DELETE','OPTIONS'], allowedHeaders: ['Content-Type','Authorization'], credentials: true, // 쿠키/자격증명 허용 maxAge: 86400 // preflight 캐시 시간(초) })); // 동적 origin 설정 예시 const whitelist = ['https://app1.example.com','https://app2.example.com']; app.use(cors({ origin: function(origin, callback){ if(!origin || whitelist.indexOf(origin) !== -1){ callback(null, true); } else { callback(new Error('Not allowed by CORS')); } }, credentials: true })); app.listen(3000); ```

5. Spring Boot(Java)에서 CORS 설정하기 1) 컨트롤러 레벨 어노테이션 ```java @RestController @RequestMapping("/api") public class ApiController { @CrossOrigin(origins = "https://frontend.example.com", methods = {RequestMethod.GET, RequestMethod.POST}, allowedHeaders = {"Content-Type", "Authorization"}, allowCredentials = "true", maxAge = 3600) @GetMapping("/data") public ResponseEntity getData() { return ResponseEntity.ok("Hello CORS"); } } ```

2) 글로벌 설정(WebMvcConfigurer) ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/ ") .allowedOrigins("https://frontend.example.com") .allowedMethods("GET","POST","PUT","DELETE","OPTIONS") .allowedHeaders("Content-Type","Authorization") .allowCredentials(true) .maxAge(3600); } } ```

6. .NET Core(Web API)에서 CORS 설정하기 ```csharp public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("MyCorsPolicy", builder => { builder.WithOrigins("https://frontend.example.com") .WithMethods("GET","POST","PUT","DELETE","OPTIONS") .WithHeaders("Content-Type","Authorization") .AllowCredentials() .SetPreflightMaxAge(TimeSpan.FromHours(1)); }); }); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseCors("MyCorsPolicy"); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ```

7. Python Flask에서 CORS 설정하기 - Flask-CORS 확장 사용: ```bash pip install flask-cors ``` ```python from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app, resources={r"/api/*": {"origins": "https://frontend.example.com"}}, supports_credentials=True, methods=["GET","POST","PUT","DELETE","OPTIONS"], allow_headers=["Content-Type","Authorization"], max_age=3600) @app.route('/api/data') def get_data(): return {'message': 'Hello CORS'} if __name__ == '__main__': app.run() ```

8. 보안 고려사항 및 팁 - 와일드카드(*) 사용 시 모든 출처가 접근 가능하므로 민감 데이터가 오가는 API에는 지양해야 합니다.

- allow-credentials를 true로 설정하면 Access-Control-Allow-Origin 헤더에 “*”를 사용할 수 없습니다.

반드시 특정 도메인을 명시해야 합니다.

- Preflight 요청(OPTIONS)에 대한 빠른 응답과 적절한 캐싱(max-age)을 설정하면 성능에 도움이 됩니다.

- 서버 측 로깅을 통해 CORS 차단 오류를 모니터링하고, 필요하다면 동적으로 허용 출처 목록(whitelist)을 관리하세요.

위와 같이 웹 서버나 애플리케이션 프레임워크별로 적절한 CORS 설정을 적용하면, 브라우저 기반의 크로스 도메인 요청을 안전하고 원활하게 처리할 수 있습니다.

작성자: 박채영 [비회원] | 작성일자: 10개월 전 2025-07-22 08:01:53
조회수: 150 | 댓글: 0 | 좋아요: 0 | 싫어요: 0
내용이 부정확하다면 싫어요를 클릭해주세요.