Blog

nginx – enable cors for specific domains

Enabling cors using nginx is simple… if you have done it once.

This is a small and quick-start example of how it can be done and how you can restrict access to a specific number domains.

 

Gotcha – SOS (read this if you want to keep sane)

Browsing around we found a number of ways to enable cors using nginx but they had a very nasty gotcha which has been described as nginx ifisevil.

The below code causes nginx to return a 404.

The reason is that nginx “if statements” are vicious and should only be used inside a location context using a return or rewrite directive.

 

Alternative (that works)

Instead of using the “if statement” in the location context to evaluate http_origin we use a map directive in our http context.

Then we use the value of the map ($cors_header) in our location context.

Apart from the Access-Control-Allow-Origin header one can also include the Access-Control-Allow-Credentials and Access-Control-Expose-Headers .

Complete code example:

 

 

Tags > ,

No Comment

Post A Comment