在Nginx中解决跨域问题,可以通过配置添加以下内容到Nginx的服务器块或特定的location块中:
location / {
# 允许指定的来源进行跨域请求
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '$http_origin';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Credentials' 'true';
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' '$http_origin';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
# ...
}
请注意替换$http_origin为你想要允许的来源。此配置允许指定的来源进行跨域请求,并设置了适当的响应头部信息以支持跨域请求。
完成配置后,重新加载或重启Nginx使配置生效。这样就可以解决Nginx中的跨域问题。
内容由零声教学AI助手提供,问题来源于学员提问




