nginx配置资源跨域

windows和linux都一样操作,到nginx的安装目录 nginx/conf下,找到nginx.conf文件,用记事本打开。
在一个sever内部加上如下代码:

        add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
    add_header 'Access-Control-Allow-Headers' 'Content-Type';

例如,这样加(各自服务器配置不同,看情况添加):

    server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        location ~.(html|js|css|png|gif|pdf)$ {
            root   html;
            index  index.html index.htm;

        }
        location / {
            root   html;
            index  index.html index.htm;
            add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
        add_header 'Access-Control-Allow-Headers' 'Content-Type';
        }

然后重启nginx就行了。

注意:
这个跨域配置不能配置多个,只能配置一个。如果你的服务器其他web服务也配置了跨域,那nginx就不要配置了。

否则还是会报跨域:

The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.

其中:Access-Control-Allow-Origin * 中的*可以换成域名,意思是只对这个域名开放跨域,如果要开放多个域名,就用英文逗号,连接。如果用*,就代表任何域名都可以请求服务器资源。
例如:

Access-Control-Allow-Origin  www.baidu.com,www.taobao.com

如果您觉得上面的内容对您有帮助,可以打赏支持一下!

打赏

关键词:Linuxnginx

网友留言(0 条)

发表评论

验证码