How to Configure nginx to Allow Cross-Origin Requests
This post was translated from Chinese by AI. If anything reads oddly, the Chinese original is authoritative. 中文原文
To allow cross-origin requests, add the following to your nginx configuration file:
location / {
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';
if ($request_method = 'OPTIONS') {
return 204;
}
}
This configuration allows cross-origin requests from all origins and supports the GET, POST, and OPTIONS methods. The 'Access-Control-Allow-Headers' field specifies the allowed request headers; requests with headers outside this list will be rejected. If the client sends an OPTIONS request, nginx immediately returns HTTP status code 204, indicating that the request is allowed.
Last updated 2024-01-14
Comments 0