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

Chr*_*Kee 205 nginx cors

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


笔记:

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

hel*_*inz 224

Nginx 必须使用http://wiki.nginx.org/NginxHttpHeadersModule(Ubuntu和其他一些 Linux 发行版的默认设置)编译。然后你可以这样做

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

  • 该模块似乎是默认编译的(至少在 Ubuntu 上)。 (8认同)
  • 我们应该把这个位置指令放在哪个文件和位置? (2认同)
  • 它对我不起作用。Nginx 1.10.0,Ubuntu 16.04 (2认同)

Chr*_*Kee 53

wildcard cors

A more up-to-date answer:

#
# 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';
     }
}
Run Code Online (Sandbox Code Playgroud)

source: 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.
Run Code Online (Sandbox Code Playgroud)

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

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


访问控制允许凭据

如果您在 CORS 请求中使用 Access-Control-Allow-Credentials,您会希望您所在位置的 cors 标头接线与此类似。由于源必须与客户端域匹配,因此通配符不起作用。

        if ($http_origin = ''){
            set $http_origin "*";
        }

        proxy_hide_header Access-Control-Allow-Origin;
        add_header Access-Control-Allow-Origin $http_origin;
Run Code Online (Sandbox Code Playgroud)

  • 请避免在 nginx 中使用 `if` - [即使官方手册也不鼓励它](https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/)。 (7认同)
  • 我想补充一点,向所有 `add_header` 添加 `always` 选项很有用,以便为非 200 响应添加标头。从 nginx 1.7.5 开始:https://nginx.org/en/docs/http/ngx_http_headers_module.html (5认同)

gan*_*est 24

这是我写的文章,它避免了 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
    ....
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 根据 SF 政策,您需要将信息复制到帖子中,而不仅仅是链接到它。网站随时可能消失,这将是信息丢失。 (3认同)
  • 考虑使用状态代码“204 No content”,因为它看起来更合适。 (3认同)
  • 有效点@tim,已更新以包含代码 (2认同)

lai*_*son 13

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

location / {
    add_header 'Access-Control-Allow-Origin' '*' always;
}
Run Code Online (Sandbox Code Playgroud)

文档

如果指定了 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)。参数值可以包含变量。


小智 11

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

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

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

默认情况下,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;
Run Code Online (Sandbox Code Playgroud)

到我的etc/nginx/mime.types档案。如上所述,上述解决方案随后奏效。

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

小智 7

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

sudo apt-get install nginx-extras
Run Code Online (Sandbox Code Playgroud)

然后在 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;
    }
}
Run Code Online (Sandbox Code Playgroud)