当前位置:首页 > nginx > 正文

nginx允许跨域访问(nginx 代理解决跨域问题分析)

  • nginx
  • 2024-04-05 15:50:08
  • 9628
Nginx允许跨域访问
跨域资源共享(CORS)是一种机制,它允许浏览器从不同域上的服务器请求资源。 为了允许跨域访问,需要在服务器端进行配置。
nginx 允许跨域访问的配置
1. 允许所有来源(通配符):
nginx
add_header 'Access-Control-Allow-Origin' '';
2. 允许特定来源:
nginx
add_header 'Access-Control-Allow-Origin' 'http://example.com';
3. 允许证书:
nginx
add_header 'Access-Control-Allow-Credentials' 'true';
4. 允许方法:
nginx
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
5. 允许标头:
nginx
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
6. 缓存预检请求:
nginx
add_header 'Access-Control-Max-Age' '3600';
示例:允许来自 http://example.com 域的跨域 POST 请求
nginx
server {
listen 80;
add_header 'Access-Control-Allow-Origin' 'http://example.com';
add_header 'Access-Control-Allow-Methods' 'POST';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
add_header 'Access-Control-Max-Age' '3600';
location / {
# ...
}
}
其他注意事项:
对于复杂请求(例如涉及凭据的请求),浏览器将在实际请求之前发送一个预检请求(OPTIONS)。
服务器需要响应预检请求,指示它允许哪些方法和标头。