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


158

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


笔记:

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


4
啊终于找到了答案的位置/ {add_header Access-Control-Allow-Origin“ *”; }
克里斯·麦基

Answers:


182

Nginx必须使用http://wiki.nginx.org/NginxHttpHeadersModule进行编译(在Ubuntu和其他一些Linux发行版中是默认设置)。那你可以做

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

按照你想要情况下,这说明要实现在Apache相同的解决方案:stackoverflow.com/questions/11616306/...
camilo_u

6
该模块似乎默认情况下已编译(至少在Ubuntu上)。
史蒂夫·本内特

1
也默认在亚马逊Linux仓库上编译
Ross

1
我们应该在哪个文件和位置中放置这个位置指令?
Sumit Arora

1
它对我不起作用。Nginx 1.10.0,Ubuntu 16.04
Omid Amraei

36

最新的答案:

#
# 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


1
有没有办法不必在每个位置重复这些行?我们可以将其放在服务器{}块下面吗?
geoyws,2015年

@geoyws(没有@我没有收到通知);您可以将其放在位置上方,就可以了:)
克里斯·麦基

这里缺少access-control-expose-headers
chovy

3
请避免if在Nginx中使用,即使官方手册也不建议使用
汇总

1
我想补充一点,将always选项添加到所有内容很有用,add_header这样也可以为非200响应添加标头。从nginx 1.7.5开始:nginx.org/en/docs/http/ngx_http_headers_module.html
Mitar

11

这是我写的文章,它避免了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
    ....
  }
}

2
根据SF策略,您需要将信息复制到帖子中,而不仅仅是链接到帖子。网站可以随时消失,这将丢失信息。
蒂姆(Tim)

1
有效点@tim,已更新为包括代码
gansbrest

考虑使用状态码,204 No content因为它似乎更合适。
Slava Fomin II

7

首先,让我说@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档案。如前所述,以上解决方案就可以了。


2
我通常会指示人们检查H5BP上的mime类型文件github.com/h5bp/server-configs-nginx/blob/master/mime.types :)
克里斯·麦基

4

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

sudo apt-get install nginx-extras

然后在nginx.conf文件中使用more_set_headers,我将示例粘贴到下面

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

1

在某些情况下,您需要使用add_header指令always来覆盖所有 HTTP响应代码。

location / {
    add_header 'Access-Control-Allow-Origin' '*' always;
}

文档

如果指定了always参数(1.7.5),则无论响应代码如何,都将添加标头字段。

如果响应代码等于200、201(1.3.10),204、206、301、302、303、304、307(1.1.16、1.0.13)或308(1.13),则将指定字段添加到响应标头.0)。参数值可以包含变量。


0

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

在/ 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


这如何帮助nginx提供静态文件?
沃尔夫

我使用nginx作为反向代理来服务Rails 5应用程序。这是一种特殊情况,其中CORS限制不是来自nginx,而是来自其背后的原始Rails App。
user9869932 '18 -10-3
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.