Nginx에서 location 블록 안에서는 여러개의 if 지시문을 중첩하여 사용할 수 없습니다. 하지만, 단일 if 지시문은 location 내에서 사용할 수 있습니다.
제시된 문제를 해결하려면, 복합 조건의 각 부분을 계산하여 하나의 변수에 저장하고, 그 변수를 기반으로 if 문을 작성해야 합니다.
다음은 수정된 구성 예제입니다:
location / {
# ... [other configuration]
# Initialize variables
set $cors 1;
set $preflight 0;
# Determine if CORS headers should be added
if ($http_origin = 'http://localhost:8888') {
set $cors 0;
}
# Check for OPTIONS request
if ($request_method = 'OPTIONS') {
set $preflight 1;
}
# Determine the combined condition
set $condition "${cors}${preflight}";
# Apply CORS headers based on the combined condition
if ($condition = '10') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
# Handle preflight requests separately
if ($condition = '11') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
# ... [rest of the configuration]
}
여기에서는 $condition 변수를 사용하여 복합 조건을 계산하고, 그 값을 기반으로 각각의 if 지시문을 작성했습니다.