跨域定义
跨域(Cross-Origin Resource Sharing, CORS)是浏览器的一种安全机制,用于限制不同源(协议、域名、端口)之间的资源访问。当浏览器从一个域名(https://example.com
)向另一个域名(https://api.example.com
)发起请求时,如果协议(http/https
)、域名或端口不同,就会触发 跨域限制。此时,浏览器会先发送 预检请求(OPTIONS),检查目标服务器是否允许跨域访问。
nginx如果配置跨域
Nginx 作为反向代理服务器,可以通过设置 HTTP 响应头来实现跨域访问控制。
Nginx 通过 add_header
指令设置 CORS 相关响应头,主要涉及以下几个关键头:
HTTP 响应头 | 作用 |
---|---|
Access-Control-Allow-Origin |
允许访问的源(如 https://example.com 或 * ) |
Access-Control-Allow-Methods |
允许的 HTTP 方法(如 GET, POST, OPTIONS ) |
Access-Control-Allow-Headers |
允许的请求头(如 Content-Type, Authorization ) |
Access-Control-Allow-Credentials |
是否允许发送 Cookie(true /false ) |
Access-Control-Max-Age |
预检请求缓存时间(单位:秒) |
常见跨域配置示例
在 Nginx 的 server
或 location
块中添加以下响应头内容,以下示例是在localtion区域中添加。
allow-origin可以不用明确的域名,用*,但前端发磅凭据cookie之类的除外。
allow-methods可以不枚举,简写为*
allow-headers也可以不枚举,简为*。
credentials设置为true,保障后端应用服务不泄露敏感信息。
设置max-age,减少重复的options请求。
location / { # 允许所有域名跨域访问(不推荐生产环境使用) add_header 'Access-Control-Allow-Origin' '*'; # 允许指定域名跨域访问(推荐) # add_header 'Access-Control-Allow-Origin' 'https://example.com'; # 允许的 HTTP 方法(GET, POST, OPTIONS 等) add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # 允许的请求头 add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization'; # 预检请求(OPTIONS)的缓存时间 add_header 'Access-Control-Max-Age' 1728000; # 允许浏览器在跨域请求中携带凭据(如 Cookie) # add_header 'Access-Control-Allow-Credentials' 'true'; # 其他配置... }
完整配置文件
server { listen 80; server_name api.liuguohua.com; location / { # 允许的域名(需明确指定,不能为 '*' 如果使用 Credentials) add_header 'Access-Control-Allow-Origin' 'https://liuguohua.com'; # 允许的方法和头 add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Custom-Header'; # 允许凭据 add_header 'Access-Control-Allow-Credentials' 'true'; # 处理 OPTIONS 请求 if ($request_method = 'OPTIONS') { add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } # 代理到后端服务(如需要) proxy_pass http://backend_server001; } }
跨域效果测试
- 使用
curl
检查响应头:curl -I -X OPTIONS http://api.example.com
检查返回头是否包含:
Access-Control-Allow-Origin: https://example.com Access-Control-Allow-Methods: GET, POST, OPTIONS
- 浏览器开发者工具
在Network
标签查看请求是否返回正确的 CORS 头。
声明:欢迎大家光临本站,学习IT运维技术,转载本站内容,请注明内容出处”来源刘国华教育“。如若本站内容侵犯了原著者的合法权益,请联系我们进行处理。