nginx 配置跨域
2025-03-23 10:31:22
101
参考资料
nginx 配置跨域
在 Nginx 中配置跨域可以通过在配置文件中添加以下内容来实现:
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';
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 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
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:允许跨域请求的源,*表示允许所有域名访问。Access-Control-Allow-Methods:允许的 HTTP 方法。Access-Control-Allow-Headers:允许的请求头。Access-Control-Max-Age:预检请求的缓存时间(秒)。Access-Control-Expose-Headers:允许客户端访问的响应头。
注意:
将
yourdomain.com替换为你的实际域名。如果只需要允许特定域名跨域,可以将
*替换为具体的域名,例如https://example.com。
配置完成后,重新加载 Nginx 配置:
sudo nginx -s reload

