题 如何在NGINX中添加Access-Control-Allow-Origin?


如何设置Access-Control-Allow-Origin标头,以便在主域中使用子域中的网络字体?


笔记:

您将在HTML5BP服务器配置项目中找到大多数HTTP服务器的此标头和其他标头的示例 https://github.com/h5bp/server-configs


133
2017-07-20 22:57




啊终于找到了答案位置/ {add_header Access-Control-Allow-Origin“*”; } - Chris McKee
ng4free.com/... - Jaydeep Gondaliya


答案:


Nginx必须编译 http://wiki.nginx.org/NginxHttpHeadersModule (默认在Ubuntu和其他一些Linux发行版上)。然后你就可以做到这一点

location ~* \.(eot|ttf|woff|woff2)$ {
    add_header Access-Control-Allow-Origin *;
}

157
2017-09-01 00:25



如果您想要在apache上实现相同的解决方案,请按照此说明操作: stackoverflow.com/questions/11616306/... - camilo_u
该模块似乎默认编译(至少在Ubuntu上)。 - Steve Bennett
也默认编译在amazon linux repo上 - Ross
我们应该在哪个文件和位置放置此位置指令? - Sumit Arora
它对我不起作用。 Nginx 1.10.0,Ubuntu 16.04 - Omid Amraei


一个更新的答案:

#
# Wide-open CORS config for nginx
#
location / {
     if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        #
        # Om nom nom cookies
        #
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
     }
     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
}

资源: https://michielkalkman.com/snippets/nginx-cors-open-configuration.html

您可能还希望添加 Access-Control-Expose-Headers (采用与Access-Control-Allow-Headers相同的格式),以便将自定义和/或“非简单”标头公开给ajax请求。

Access-Control-Expose-Headers (optional) - The XMLHttpRequest 2 object has a 
getResponseHeader() method that returns the value of a particular response 
header. During a CORS request, the getResponseHeader() method can only access 
simple response headers. Simple response headers are defined as follows:

    Cache-Control
    Content-Language
    Content-Type
    Expires
    Last-Modified
    Pragma
 If you want clients to be able to access other headers, you have to use the
 Access-Control-Expose-Headers header. The value of this header is a comma-
 delimited list of response headers you want to expose to the client.

- http://www.html5rocks.com/en/tutorials/cors/

配置其他Web服务器 http://enable-cors.org/server.html


29
2017-08-24 11:01



任何方式不必为每个位置重复这些行?我们可以将它放在服务器{}块下吗? - geoyws
@geoyws(没有@我没有收到通知);你可以把它放在上面的位置,那很好:) - Chris McKee
这里缺少access-control-expose-headers - chovy
@chovy它是一个可选的标题,用于向ajax请求公开非默认值,但我可以看到它如此正式添加绊倒了人们。钽 - Chris McKee
请避免使用 if 在nginx中 - 甚至官方手册也不鼓励它。 - aggregate1166877


首先,让我说@hellvinz答案对我有用:

location ~* \.(eot|ttf|woff|woff2)$ {
    add_header Access-Control-Allow-Origin *;
}

但是,我已经决定用一个单独的答案回答这个问题,因为我只是在花了大约十个小时寻找解决方案之后才设法使这个解决方案工作。

似乎默认情况下Nginx没有定义任何(正确的)字体MIME类型。依照指示 这个故事 我发现我可以添加以下内容:

application/x-font-ttf           ttc ttf;
application/x-font-otf           otf;
application/font-woff            woff;
application/font-woff2           woff2;
application/vnd.ms-fontobject    eot;

对我来说 etc/nginx/mime.types 文件。如上所述,上述解决方案随后起作用。


6
2018-01-04 15:24



我通常会指示人们检查H5BP上的mime类型文件 github.com/h5bp/server-configs-nginx/blob/master/mime.types :) - Chris McKee


这是我写的文章,它避免了GET | POST的一些重复。它应该让你在Nginx中使用CORS。

nginx访问控制允许原点

以下是帖子中的示例代码段:

server {
  listen        80;
  server_name   api.test.com;


  location / {

    # Simple requests
    if ($request_method ~* "(GET|POST)") {
      add_header "Access-Control-Allow-Origin"  *;
    }

    # Preflighted requests
    if ($request_method = OPTIONS ) {
      add_header "Access-Control-Allow-Origin"  *;
      add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
      return 200;
    }

    ....
    # Handle request
    ....
  }
}

5
2018-04-17 21:15



根据SF政策,您需要将信息复制到帖子中,而不仅仅是链接到帖子。网站可以随时消失,这将是信息的丢失。 - Tim
有效点@tim,已更新以包含代码 - gansbrest


Nginx的传统add_header指令不适用于4xx响应。由于我们仍然想为它们添加自定义标头,我们需要安装ngx_headers_more模块才能使用more_set_headers指令,该指令也适用于4xx响应。

sudo apt-get install nginx-extras

然后用 more_set_headers 在nginx.conf文件中,我在下面粘贴了我的示例

server {
    listen 80;
    server_name example-site.com;
    root "/home/vagrant/projects/example-site/public";

    index index.html index.htm index.php;

    charset utf-8;

    more_set_headers 'Access-Control-Allow-Origin: $http_origin';
    more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE, HEAD';
    more_set_headers 'Access-Control-Allow-Credentials: true';
    more_set_headers 'Access-Control-Allow-Headers: Origin,Content-Type,Accept,Authorization';

    location / {
        if ($request_method = 'OPTIONS') {
            more_set_headers 'Access-Control-Allow-Origin: $http_origin';
            more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE, HEAD';
            more_set_headers 'Access-Control-Max-Age: 1728000';
            more_set_headers 'Access-Control-Allow-Credentials: true';
            more_set_headers 'Access-Control-Allow-Headers: Origin,Content-Type,Accept,Authorization';
            more_set_headers 'Content-Type: text/plain; charset=UTF-8';
            more_set_headers 'Content-Length: 0';
            return 204;
        }
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/example-site.com-error.log error;

    sendfile off;

    client_max_body_size 100m;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
    }

    location ~ /\.ht {
        deny all;
    }
}

2
2018-05-30 10:41





就我而言,使用Rails 5,唯一可行的解​​决方案是添加 rack-cors 宝石。像这样:

在/ Gemfile中

# Gemfile
gem 'rack-cors'

在config / initializers / cors.rb中

# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'localhost:4200'
    resource '*',
      headers: :any,
      methods: %i(get post put patch delete options head)
  end
end

资源: https://til.hashrocket.com/posts/4d7f12b213-rails-5-api-and-cors


0
2018-05-04 23:07



这有助于nginx提供静态文件吗? - Walf
我使用nginx作为反向代理来为rails 5 app提供服务。这是一个特殊情况,其中CORS限制不是来自nginx,而是来自其背后的原始Rails App。 - xyz