A lot of people have problems with Nginx across domains, but my problem is:

  • The client is at www.a.com
  • The server is at www.b.com
  • Nginx at www.c.com

In order to access www.c.com’s fetch client www.a.com to request data from www.b.com, I need to configure Nginx as follows (important part) :

location / {
    add_header 'Access-Control-Allow-Origin' $http_origin;
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requ ested-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;
    }
    root   html;
    proxy_pass http://xxx:8000/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_connect_timeout 5;
}
Copy the code

Don’t forget to change the proxy_pass http://xxx:8000/ address to your service address. Of course, your client can not request your service address, but Nginx address, so that you can solve the cross-domain problem.