Apache与NGINX下Control-Allow-Origin * 设置 - 风屿岛
Apache与NGINX下Control-Allow-Origin * 设置 - 风屿岛

Apache与NGINX下Control-Allow-Origin * 设置

2019-12-22 超级管理员
AI摘要

文章主要介绍了如何设置`Access-Control-Allow-Origin` HTTP头解决跨域问题。在Apache配置中通过`mod_headers`模块添加相关头信息,在NGINX中通过`add_header`指令设置,在HTML中通过`meta`标签设置,在Java和.net中通过代码设置响应头。文章指出`Access-Control-Allow-Origin`可指定允许跨域访问的域名,使用`*`表示所有域名均可访问,并列举了不同技术实现的具体方法。

介绍

网站一般在需要共享资源给其他网站时(跨域传递数据),才会设置access-control-allow-origin HTTP头
设置Access-Control-Allow-Origin,可以解决多域名跨域问题
Access-Control-Allow-Origin * 等所有网站都可以跨域访问
Access-Control-Allow-Origin gqink.cn 允许gqink.cn跨域访问

Apache
<ifmodule mod_headers.c>

    Header set Access-Control-Allow-Origin: "*"

    Header set Access-Control-Allow-Methods: "GET,POST,PUT,DELETE,OPTIONS"

    Header set Access-Control-Allow-Headers: "Content-Type"

</ifmodule>

添加到httpd.conf最下面

NGINX
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'PUT,POST,GET,DELETE,OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With';

location / {  
  add_header Access-Control-Allow-Origin *;
  add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
  add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
} 

将代码添加到NGINX

HTML
<meta http-equiv="Access-Control-Allow-Origin" content="*">

Java
response.setHeader("Access-Control-Allow-Origin", "*"); 

.net
Response.AddHeader("Access-Control-Allow-Origin", "*");
返回首页
最后更新: 2025-12-23

评论

发表评论

设置

主题

字体连字

HDR