Fix Nginx CORS: Step-by-Step Configuration Guide

To solve the cross-origin issue of Nginx, you can choose from the following several methods:

  1. Add cross-origin related headers in the Nginx configuration file: You can enable cross-origin access by adding the following content in the 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';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
    
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }
}
  1. By utilizing Nginx’s proxy feature, you can resolve cross-origin issues when your frontend and backend services are under different domain names. You can proxy the frontend requests to the backend domain to prevent cross-origin problems.
location /api/ {
    proxy_pass http://backend-server;
}
  1. Utilizing Nginx’s reverse proxy feature: If your frontend and backend services are on the same domain but different ports, you can use Nginx’s reverse proxy feature to solve the cross-origin issue. By mapping the frontend requests to the backend ports, it helps in avoiding cross-origin problems.
location / {
    proxy_pass http://backend-server:8080;
}

The methods mentioned above are some common ways to solve Nginx cross-origin issues. Choose the appropriate method according to your actual situation for configuration.

bannerAds