
뒤에 PHP-FPM 인스턴스가 있는 NGINX가 있습니다. OPTIONS
파일 시스템에 파일이 존재하는 경로에 대한 요청은 NGINX에서 처리해야 합니다. 이러한 요청의 경우 NGINX는 Access-Control-*
CORS 헤더를 반환해야 합니다. OPTIONS
파일이 없는 요청은 PHP-FPM으로 전달되어야 합니다.
논리는 다음과 같은 내용이어야 합니다.
location / {
# In this case: Check if file exists
# - yes: return CORS headers
# - no: pass request to PHP-FPM
if ($request_method = 'OPTIONS') {
# This causes an error
try_files @cors;
}
# Normal request handling for all non-OPTIONS requests:
# Try to serve file directly, fallback to index.php if file does not exist
try_files $uri /index.php$is_args$args;
}
location @cors {
if (-f $request_filename) {
more_set_headers "Access-Control-Allow-Credentials: true";
more_set_headers "Access-Control-Allow-Origin: example.com";
more_set_headers 'Access-Control-Allow-Methods: POST, GET, DELETE, PUT, OPTIONS';
more_set_headers 'Access-Control-Allow-Headers: content-type,ngsw-bypass';
more_set_headers 'Access-Control-Max-Age: 3600';
more_set_headers 'Content-Type: text/plain; charset=UTF-8';
more_set_headers 'Content-Length: 0';
return 204;
}
try_files /index.php$is_args$args;
}
location ~ ^/index\.php(/|$) {
fastcgi_pass localhost:9000;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param SCRIPT_FILENAME /var/www/public/index.php;
fastcgi_param DOCUMENT_ROOT /var/www/public;
fastcgi_param HTTPS $fastcgi_param_https;
# Prevents URIs that include the front controller. This will 404:
# http://domain.tld/index.php/some-path
# Remove the internal directive to allow URIs like this
internal;
}
하지만 이것은 작동하지 않습니다. 명령문 try_files
내에서는 허용되지 않습니다 ( if
[emerg] 1#1: "try_files" 지시문은 여기에서 허용되지 않습니다).
답변1
error_page
지시문을 사용하여 파일 시스템에 파일이 존재하는 경로에 대한 OPTIONS 요청을 처리 할 수 있습니다 .
location / {
# Try to serve file directly, fallback to index.php if file does not exist
try_files $uri /index.php$is_args$args;
# Handle OPTIONS requests for paths for which a file exists in the file system
if ($request_method = 'OPTIONS') {
if (-f $request_filename) {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
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;
}
}
}
# Pass all other requests to PHP-FPM
location ~ \.php$ {
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
지시문 은 파일이 존재하지 않는 경우 try_files
대체하여 파일을 직접 제공하는 데 사용됩니다 . index.php
블록 if
은 요청 방법이 OPTIONS인지, 요청한 경로에 파일이 있는지 확인합니다. 두 조건이 모두 true인 경우 NGINX는 필요한 CORS 헤더를 응답에 추가하고 204 No Content 상태 코드를 반환합니다.