---
title: "nginx配置跨域设置"
author: "yjph83"
date: "2016-07-11T13:14:39Z"
tags: ["CORS", "nginx"]
categories: ["开源软件"]
slug: "nginx"
draft: false
lastmod: "2017-05-08T17:05:17Z"
id: 2310456
url: "https://yjph83.iteye.com/blog/2310456"
---

在nginx.conf 配置文件中设置如下！

location /

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,userId,token';

                 add\_header 'Access-Control-Max-Age' 3600;

                 #add\_header 'Content-Type' 'text/plain charset=UTF-8';  

                 add\_header 'XDomainRequestAllowed' '1';

           }

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,userId,token';

                 add\_header 'Access-Control-Max-Age' 0;

                 #add\_header 'Content-Type' 'text/plain charset=UTF-8';

                 add\_header 'XDomainRequestAllowed' '1';

           }

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,userId,token';

                 add\_header 'Access-Control-Max-Age' 0;

                 #add\_header 'Content-Type' 'text/plain charset=UTF-8';

                 add\_header 'XDomainRequestAllowed' '1';

           }

 

 以上是根据具体的  POST、PUT、GET等方式的配置：

还可以直接在 server节点下直接配置：

add\_header 'Access-Control-Allow-Origin' '\*';   就是最简单的配置