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

📅 2019-12-22 👤 超级管理员
#技术文章 #建站教程 #教程 #Nginx #Apache
🤖 AI摘要

网站在需要跨域传递数据时设置Access-Control-Allow-Origin HTTP头,可解决多域名跨域问题。其值可配置为通配号*允许所有网站访问,或指定具体域名如gqink.cn仅允许该域名访问。同时需配置允许的请求方法(如GET、POST等)及请求头(如Content-Type)。文章介绍了Apache、NGINX、HTML、Java及.NET等环境中该头的具体配置方式,强调其作为跨域资源共享核心机制的作用,通过合理配置实现安全的跨域数据交互。

介绍

网站一般在需要共享资源给其他网站时(跨域传递数据),才会设置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-17

您正在浏览AMP加速版本,评论功能在完整版中可用。

查看完整版本