Search code examples
nginxcors

How to add a header that resolves CORS error in nginx api calling?


I have two subdomain behind my nginx: panel.example.ir and api.example.ir While I call api.example.ir from my panel panel.example.ir, I see an error:

Access to XMLHttpRequest at 'https://api.example.ir/api/test/pre_sale_customer_project_view?offset=0&limit=5&order=created_at.desc' from origin 'https://panel.example.ir' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Also when I add add_header Access-Control-Allow-Origin *; to my api nginx conf, I have another error as below!

Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'panel.example.ir, *', but only one is allowed.

What can I do now?


Solution

  • Maybe have a look at this post. With add_header you will stack the header values when you use it as proxy. In the post it's described how you could hide the original header to replace it with a given one from nginx.

    How to overwrite http Content-Disposition header in nginx.conf location block?

    So in your case maybe use:

    proxy_hide_header Access-Control-Allow-Origin;
    add_header Access-Control-Allow-Origin panel.example.ir;
    

    or you configure your application so it is always responding with the correct headers.