you can use the error_page
directive to handle the OPTIONS requests for paths for which a file exists in the file system.
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;
}
the try_files
directive is used to serve files directly, with fallback to index.php
if the file does not exist. The if
block checks if the request method is OPTIONS and if a file exists at the requested path. If both conditions are true, NGINX will add the necessary CORS headers to the response and return a 204 No Content status code.