How to enable CORS in nginx?

Published on Aug. 22, 2023, 12:19 p.m.

To enable CORS in nginx, you can use the add_header directive to add the Access-Control-Allow-Origin header to the HTTP response. Here’s an example of how to set it up:

location / {
    add_header 'Access-Control-Allow-Origin' '*';
    # your other directives here
}

In this example, the Access-Control-Allow-Origin header is set to * to allow any origin to access the resources served by nginx. You can also set it to a specific domain or a list of domains to restrict access to only those domains.

Note that enabling CORS can increase the security risks for your application, so it should be done with caution. It’s recommended to restrict access to only the domains that need to access your resources and to use HTTPS for increased security.

Also, keep in mind that using the add_header directive with if statements can be tricky, as if statements aren’t recommended in location blocks. It’s better to use map or separate location blocks to handle the add_header directive for different paths or conditions.

Tags: