nginx设置跨域访问的方法
墨初 互联知识 2765阅读
在nginx中默认是禁止被跨域访问的,如果想要nginx被跨域访问是可以通过修改nginx的配置文件来实现的,下面就说一说在nginx中通过配置文件来实现跨域访问的方法。
nginx允许跨域访问的方法
方法1:
Nginx允许跨域访问需要在Nginx配置文件中进行设置,在nginx.conf文件中的http部分中,可以使用add_header指令来配置允许跨域访问的响应头。
例:
http {
// 其他配置
add_header Access-Control-Allow-Origin *;
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';
add_header Access-Control-Allow-Credentials true;
}代码解释:
Access-Control-Allow-Origin:指定允许的跨域来源,可以是一个具体的域名,也可以使用通配符“*”表示允许任意跨域来源。
Access-Control-Allow-Methods:指定允许的跨域请求方法。
Access-Control-Allow-Headers:指定允许跨域请求头。
Access-Control-Allow-Credentials:指定是否允许跨域请求发送Cookie。
方法2:
在nginx.conf文件中的server部分中也可以通过下面的代码来实现。
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-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 1728000;
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-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
add_header 'Access-Control-Allow-Credentials' 'true';
}
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-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
add_header 'Access-Control-Allow-Credentials' 'true';
}
# 处理其他请求
}
}以上就是nginx中设置允许跨域访问的方法。