跨域资源共享(Cross-Origin Resource Sharing, CORS)是现代Web开发中常见的需求。以下是在Nginx服务器上配置CORS的详细方法:
在Nginx配置文件中(通常在nginx.conf
或站点配置文件中)添加以下内容:
server {
listen 80;
server_name example.com;
location / {
# 允许所有来源访问
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-Max-Age' 1728000;
# 允许浏览器在跨域请求中暴露响应头
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
# 处理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;
}
# 其他配置...
}
}
如果只需要允许特定域名访问,可以替换通配符*
:
add_header 'Access-Control-Allow-Origin' 'https://yourdomain.com';
如果需要根据请求来源动态设置允许的域名:
map $http_origin $cors_origin {
default "";
"~^https://(domain1\.com|domain2\.com)$" $http_origin;
}
server {
# ...其他配置
location / {
if ($cors_origin) {
add_header 'Access-Control-Allow-Origin' $cors_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
}
# ...其他CORS配置
}
}
如果需要支持带凭证(cookie、HTTP认证等)的跨域请求:
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Origin' 'https://yourdomain.com'; # 不能使用通配符*
server {
listen 80;
server_name api.example.com;
location / {
# 动态允许多个来源
if ($http_origin ~* (https://example.com|https://app.example.com)) {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
}
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
add_header 'Access-Control-Max-Age' 1728000;
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;
}
}
sudo nginx -s reload
*
作为允许的来源通过以上配置,你的Nginx服务器将能够正确处理跨域请求,同时保持必要的安全性。