弹琵琶又见当年镜前你梳头
拨一首满花春秀
今日月下再醉孤酒
雨落枝头年复一年谁白发留
让爱随相思入梦左右
梦见我们还挽着手
🎵 马天宇《青衣》
在现代web开发中,跨源资源共享(CORS,Cross-Origin Resource Sharing)是一个常见的需求。对于前后端分离的项目,前端应用常常需要从不同的源(域名、协议或端口)请求后端服务。而出于安全考虑,浏览器的同源策略默认会阻止这类请求。幸运的是,通过在Nginx中配置适当的策略,我们可以允许特定的跨域请求,本文将指导你如何做到这一点。
什么是CORS
CORS是一个W3C标准,允许服务器指定哪些来源可以访问其资源。这是通过服务器发送一系列CORS相关的HTTP响应头来实现的。这些响应头决定了哪些网站可以请求服务器的资源,以及哪些HTTP请求方法和头部字段被允许。
在Nginx中配置CORS
配置Nginx以支持CORS相对简单。下面是一个基本的配置示例,展示了如何在Nginx服务器上为所有请求启用CORS。
基本CORS配置
打开你的Nginx配置文件,这通常位于/etc/nginx/nginx.conf
,或者是包含在某个特定站点配置文件中,位于/etc/nginx/sites-available/目录下。找到你想要启用CORS的server块,在其中添加如下配置:
server {listen 80;server_name yourdomain.com;location / {if ($request_method = 'OPTIONS') {add_header 'Access-Control-Allow-Origin' '*';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';## Custom headers and headers various browsers *should* be OK with but aren't#add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';## Tell client that this pre-flight info is valid for 20 days#add_header 'Access-Control-Max-Age' 1728000;add_header 'Content-Type' 'text/plain; charset=utf-8';add_header 'Content-Length' 0;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,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';}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,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';}}
}
这段配置实现了以下功能:
- 允许所有来源(
Access-Control-Allow-Origin: *
)访问资源。在生产环境中,出于安全考虑,你可能想将它更改为特定的域名。 - 允许GET、POST和OPTIONS方法。
- 定义了哪些HTTP请求头被允许。
- 对于OPTIONS预检请求,返回204状态码,并告诉客户端预检请求的结果可以缓存20天(Access-Control-Max-Age)。
注意事项
在配置CORS时,需要注意Access-Control-Allow-Origin不能设置为*如果同时设置了Access-Control-Allow-Credentials: true。因为在带凭证的请求中,*会被视为不安全的。
OPTIONS请求称为预检请求,用于检查服务器是否允许跨域请求。正确处理这类请求对于支持C