---
title: "nginx中配置跨域支持功能"
author: "tkggft"
date: "2015-10-14T10:49:38Z"
tags: []
categories: ["企业架构"]
slug: "nginx"
draft: false
lastmod: "2015-10-14T10:51:55Z"
id: 2249016
url: "https://tkggft.iteye.com/blog/2249016"
---

在nginx.conf中配置

http {  
  ......  
  add\_header Access-Control-Allow-Origin \*;  
  add\_header Access-Control-Allow-Headers X-Requested-With;  
  add\_header Access-Control-Allow-Methods GET,POST,OPTIONS;  
  ......  
}

这样就可以实现GET,POST,OPTIONS的跨域请求的支持  
也可以 add\_header Access-Control-Allow-Origin http://test.51testing.com; --指定允许的url;

配置项详细解释：[w3c-Cross-Origin Resource Sharing](http://www.w3.org/TR/cors/#access-control-allow-methods-response-header)

 

 

 

 

 

 

 

在Nginx location 里加上如下代码可以解决js 请求跨域问题

 

 

if ($request\_method = 'OPTIONS') { 

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-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; 

return 200; 

}

 

if ($request\_method = 'POST') {

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-Mx-ReqToken,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-Credentials' 'true'; 

add\_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; 

add\_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

}