2

I'm have an Rails application with Angular. I'm using nginx and passenger as a server. The idea is that angular makes requests to the api.app.com. When I try to do this I get this error.

XMLHttpRequest cannot load https://api.app.com/api/some_resource. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.app.com' is therefore not allowed access. The response had HTTP status code 404.`

My current nginx configuration handles CORS requests this way:

server {
    location / {
        set $cors '';

        if ($http_origin ~* 'https?://(localhost|www\.app-staging\.com|www\.app\.com|api.app.com|app.com)') {
            set $cors 'true';
        }

        proxy_set_header Host $http_host;

        if ($cors = 'true') {
            add_header 'Access-Control-Allow-Origin' "$http_origin";
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            #add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqTok$
        }
    }
}

What I'm doing wrong?

1 Answer 1

2

You are wrapping the match with ', which is not required. Also, remember that the . is a special value in a regular expression.

if ($http_origin ~* (localhost|www\.app-staging\.com|www\.app\.com|api\.app\.com|app\.com)) {
  set $cors 'true';
}

Remember to restart the server or reload the configuration after the change.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.