通过 add_header 命令可以使特定地址前缀使用跨域访问

add_header 所在位置存在覆盖情况,一般配置在 server 内这样此server下所有访问都会被添加跨域, 实际中我们的情况有些不同,是部分location需要添加跨域,部分不需要,因为那部分跨域被写其他项目写在了代码了, 如果统一加会导致浏览器报错,提示Access-Control-Allow-Origin *,* 。

比如有如下需要添加跨域的代码

location /sale/api/design {
            add_header Access-Control-Allow-Origin * always;
            add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
            add_header Access-Control-Allow-Headers 'Accept,Token,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,x-access-token,x-ca-signature-headers,x-ca-signature,x-ca-nonce,x-ca-timestamp,x-ca-alg,x-ca-key,x-ca-request-mode,x-ca-stage' always;

            if ($request_method = 'OPTIONS') {
                add_header Access-Control-Allow-Origin * always;
                add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
                add_header Access-Control-Allow-Headers 'Accept,Token,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,x-access-token,x-ca-signature-headers,x-ca-signature,x-ca-nonce,x-ca-timestamp,x-ca-alg,x-ca-key,x-ca-request-mode,x-ca-stage' always;
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain charset=utf-8';
                add_header 'Content-Length' 0;
                return 204;
            }
            if (!-f $request_filename) {
                rewrite ^/(.+)$ /index.php?$1& last;
            }
        }
location ~ \.php$
         {
            add_header Access-Control-Allow-Origin * always;
            add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS' always;
            add_header Access-Control-Allow-Headers 'Accept,Token,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,x-access-token,x-ca-signature-headers,x-ca-signature,x-ca-nonce,x-ca-timestamp,x-ca-alg,x-ca-key,x-ca-request-mode,x-ca-stage' always;
            root           /var/www/phpproject;
            fastcgi_pass  phpbackend;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /$document_root$fastcgi_script_name;
            include        fastcgi_params;
         }

这里 一定也要在 location ~ \.php$中添加 add_header, 否则还是不能跨越的。

至于 Access-Control-Allow-Headers 后面的所需要的 header参数,就根据自己的实际情况做调整, 如果header中的某项没有在这里体现,可能也会导致提示跨域错误。

(234)

Related Post