为 nginx 和 passenger 配置 CORS

Configuring CORS for nginx and passenger

我有一个 Rails 应用 Angular。我正在使用 nginx 和 passenger 作为服务器。这个想法是 angular 向 api.app.com 发出请求。当我尝试这样做时,出现了这个错误。

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.`

我当前的 nginx 配置以这种方式处理 CORS 请求:

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$
        }
    }
}

我做错了什么?

您正在用 ' 包装匹配项,这不是必需的。另外,请记住 . 是正则表达式中的一个特殊值。

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

修改后记得重启服务器或重新加载配置。