Nginx配置允许跨域

要在Nginx中配置允许跨域(Cross-Origin Resource Sharing, CORS),你需要修改Nginx的配置文件(通常是nginx.conf或者某个包含在nginx.conf中的单独的配置文件)。下面是一个基本的例子,展示了如何在Nginx中设置CORS:

  1. 打开你的Nginx配置文件。这通常是/etc/nginx/nginx.conf或者/etc/nginx/conf.d/default.conf,或者一个特定站点的配置文件在/etc/nginx/sites-available//etc/nginx/conf.d/目录下。

  2. 在你想要允许跨域请求的server块或location块中添加add_header指令。

下面是一个简单的例子,它允许来自任何源的跨域请求,并允许所有的请求方法(GET, POST, PUT, DELETE等)和请求头:

server {
 listen 80;
 server_name your.domain.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;
 }
 if ($request_method = 'POST' || $request_method = 'GET' || $request_method = 'PUT' || $request_method = 'DELETE') {
 add_header 'Access-Control-Allow-Origin' '*';
 add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
 add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
 #
 # 如果需要处理跨域Cookie,请取消下面的注释
 #
 # add_header 'Access-Control-Allow-Credentials' 'true';
 }
 # ... 其他的代理或静态文件配置 ...
 }
}

注意

  • * 允许来自任何源的请求,但在生产环境中,出于安全考虑,你应该明确指定允许的源。
  • 如果你需要处理跨域Cookie(即withCredentials设置为true的XHR/Fetch请求),则必须设置Access-Control-Allow-Credentialstrue,并且Access-Control-Allow-Origin不能设置为*,而应该是一个具体的源(如http://example.com)。
  • 在处理OPTIONS预检请求时,Nginx直接返回204状态码,这告诉浏览器请求是允许的,并且不需要实际发送请求体。
  • 请根据你的实际需求调整允许的HTTP方法和请求头。

修改完Nginx配置文件后,重新加载或重启Nginx服务以使更改生效:

sudo nginx -s reload
# 或者
sudo systemctl reload nginx
# 或者完全重启Nginx服务
sudo systemctl restart nginx
作者:dashery原文地址:https://www.cnblogs.com/ydswin/p/18193923

%s 个评论

要回复文章请先登录注册