Latest News : 亮瞎双眼的那些年!

常见的跨域配置

乱弹 admin 250 views 0 comments

htaccess文件(或者”分布式配置文件”),全称是Hypertext Access(超文本入口)。提供了针对目录改变配置的方法, 即,在一个特定的文档目录中放置一个包含一个或多个指令的文件, 以作用于此目录及其所有子目录。作为用户,所能使用的命令受到限制。管理员可以通过ApacheAllowOverride指令来设置。

允许所有域名跨域

<IfModule mod_headers.c>
   Header add Access-Control-Allow-Origin: *
</IfModule>

指定域名跨域:

<IfModule mod_headers.c>
   Header add Access-Control-Allow-Origin: "http://www.baidu.com" 
</IfModule>

指定多域名跨域:

<IfModule mod_headers.c>
   SetEnvIf Origin "http(s)?://(www.)?(baidu1.com|baidu2.com)$" AccessControlAllowOrigin=$0$1
   Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
</IfModule>


nginx 跨域配置:

location / {
   # 检查域名后缀
   if ($http_origin ~ \.test\.com) {
        add_header Access-Control-Allow-Origin $http_origin;
        add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Allow-Headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type;
        add_header Access-Control-Max-Age 1728000;
   }
   # options请求不转给后端,直接返回204
   # 第二个if会导致上面的add_header无效,这是nginx的问题,这里直接重复执行下
   if ($request_method = OPTIONS) {
        add_header Access-Control-Allow-Origin $http_origin;
        add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Allow-Headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type;
        add_header Access-Control-Max-Age 1728000;
        return 204;
   }
    
   # 其他请求代理到后端
   proxy_set_header Host $host;
   proxy_redirect off;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Scheme $scheme;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header X-Forwarded-Proto $scheme;
   proxy_pass http://xxx.xxx.xxx.xxx;
}

 

Please indicate: 无趣的人生也产生有意思的事件 » 常见的跨域配置

Hi, you must log in to comment !