I've tried to use a very popular config for nginx, which enables CORS and supports origin matching using regular expressions.
Here's my config:
server {
listen 80 default_server;
root /var/www;
location / {
if ($http_origin ~ '^http://(www\.)?example.com$') {
add_header Access-Control-Allow-Origin "$http_origin";
}
# Handling preflight requests
if ($request_method = OPTIONS) {
add_header Content-Type text/plain;
add_header Content-Length 0;
return 204;
}
}
}
However, this config must use two conditions: one to match the origin domain name and another one to capture preflight requests. So when the second condition is matched, the headers from the first conditions are not added to the response.
According to the If Is Evil official article, this is an expected behavior for nginx.
If If Is Evil
how do I enable CORS in nginx then? Or maybe there is a way to overcome this limitation somehow?
To enable CORS on NGINX, you need to use the add_header directive and add it to the appropriate NGINX configuration file. to allow access from any domain.
Simply activate the add-on and perform the request. CORS or Cross-Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs). Installing this add-on will allow you to unblock this feature.
This happens if you haven't set up CORS configuration correctly. you can fix this on you'r local machine using a plugin/extension called Allow-Control-Allow-Origin and add you'r localhost into it. The other way is to manually fix the configuration in server side.
The Nginx add_header directive allows you to define an arbitrary response header and value to be included in all response codes, which are equal to 200 , 201 , 204 , 206 , 301 , 302 , 303 , 304 , or 307 . This can be defined from within your nginx.
You can try to use map
istead of the first if
block:
map $http_origin $allow_origin {
~^http://(www\.)?example.com$ $http_origin;
}
map $http_origin $allow_methods {
~^http://(www\.)?example.com$ "OPTIONS, HEAD, GET";
}
server {
listen 80 default_server;
root /var/www;
location / {
add_header Access-Control-Allow-Origin $allow_origin;
add_header Access-Control-Allow-Methods $allow_methods;
# Handling preflight requests
if ($request_method = OPTIONS) {
add_header Content-Type text/plain;
add_header Content-Length 0;
return 204;
}
}
}
nginx will refuse to add an empty HTTP headers, so they will be added only if Origin
header is present in request and matched this regex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With