大漠知秋的加油站

  • 首页
大漠知秋的加油站
你就当我的烂笔头吧
  1. 首页
  2. Nginx
  3. 正文

Nginx 处理跨域问题

2019年1月3日 867点热度 0人点赞 0条评论
  • 常规方式
server {
	location / {
	
		......

		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';

		.......		

	}
}

有时候上面的方式会不成功,可以采用下面的方式

server {
	location / {
	
		......

		if ($request_method = 'OPTIONS') {
		    add_header 'Access-Control-Allow-Origin' '*';
		    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';
		    
		    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-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-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';
		}
		
		.......		

	}
}
标签: Nginx 跨域
最后更新:2019年1月3日

大漠知秋

唯黄昏而思烛明,唯覆雪始念日暖,唯放手方知情真,今困苦而怀峥嵘,今飘零而涌乡愁,今孑然而徒唏嘘,唏嘘成愁。

点赞
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2023 大漠知秋的加油站. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

豫ICP备16029200号-2