How to configure Nginx to support Cross-Origin Resource Sharing (CORS) for web APIs?

To configure Nginx to support Cross-Origin Resource Sharing (CORS) for web APIs, you can follow these steps:

Step 1: Edit the Nginx configuration file Open the Nginx configuration file using a text editor. The configuration file can usually be found at /etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf.

Step 2: Add CORS headers Inside the server block, add the following lines to add CORS headers:

server { ... location /api { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain charset=UTF-8'; add_header 'Content-Length' 0; return 204; } ... } ... }

This configuration will add the necessary CORS headers for all requests made to the /api endpoint. You can modify the location directive to match your specific API endpoint.

Step 3: Restart Nginx Save the changes to the configuration file and restart Nginx for the changes to take effect. Use the command sudo service nginx restart to restart Nginx.

After completing these steps, Nginx will be configured to support CORS for your web APIs. This will allow cross-origin requests to be made to your API endpoints.