nginx配置跨域访问,无法生效

  • 问题描述

最近在配置nginx跨域问题上折腾了很长时间。网址开发通常将动态资源与静态资源分开,在A的服务器上需要去加载B服务器上的静态资源时通常就会遇到跨域的问题,如下加载字体静态文件

Access to Font at 'http://bbb.cn/biz/fonts/iconfont.woff' from origin 'http://aaa.cn' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://aaa.cn' is therefore not allowed access

控制台会说访问B服务器上的资源出现跨域问题,我们可以在nginx上配置跨域请求来解决问题。

  • 指定可以跨域访问的单网址
	server {

		listen 80;
		server_name https://bbb.cn;
		location /biz/fonts/ {
			add_header Access-Control-Allow-Origin http://aaa.cn;
			add_header Access-Control-Allow-Credentials true;
			add_header Access-Control-Allow-Methods GET;
		}
	}

  • 任何网址都可以跨域访问(为了安全通常不这么配置)
	server {

		listen 80;
		server_name https://bbb.cn;
		location /biz/fonts/ {
			add_header Access-Control-Allow-Origin * ;
			add_header Access-Control-Allow-Credentials true;
			add_header Access-Control-Allow-Methods 'GET,POST,OPTIONS';
		}
	}

  • 允许多个网址跨域访问(配置一个map)
	map $http_origin $origin_list{
		default http://aaa.cn;
		"~http://ccc.cn" http://ccc.cn;
		"~http://ddd.cn" http://ddd.cn;
	}
	server {

		listen 80;
		server_name https://bbb.cn;
		location /biz/fonts/ {
			add_header Access-Control-Allow-Origin "$origin_list" ;
			add_header Access-Control-Allow-Credentials true;
			add_header Access-Control-Allow-Methods 'GET,POST,OPTIONS';
		}
	}

  • 踩坑记录

    在我配置好上述内容后,在浏览器访问时,依旧出现了跨域访问的问题,我一开始在网上疯狂搜索相关问题,修改了很多中配置方法,依旧无效。很是绝望,我甚至怀疑过时版本问题,更换了nginx版本依旧一样,最终发现,是由于浏览器的缓存问题,清除掉浏览器缓存后,正常请求到跨域访问的内容,希望遇到和为一样问题的人,不妨试试该方法。
原文地址:https://www.cnblogs.com/fate-pc/p/13370719.html