找回密码
 立即注册
查看: 11|回复: 0

nginx服务器跨域设置

[复制链接]
发表于 前天 12:52 | 显示全部楼层 |阅读模式
  1. server {
  2.     listen 80;
  3.     server_name your-api-domain.com; # 替换为你的实际域名或IP

  4.     location / {
  5.         # 核心跨域配置
  6.         add_header 'Access-Control-Allow-Origin' '*' always;                 # 允许所有源访问,生产环境建议指定具体域名
  7.         add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always; # 允许的HTTP方法
  8.         add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization' always; # 允许的请求头
  9.         add_header 'Access-Control-Allow-Credentials' 'true' always;         # 允许携带Cookie时,Access-Control-Allow-Origin不能为'*',需指定具体域名
  10.         add_header 'Access-Control-Max-Age' 1728000 always;                  # 预检请求的缓存时间(秒)

  11.         # 处理OPTIONS预检请求
  12.         if ($request_method = 'OPTIONS') {
  13.             add_header 'Access-Control-Allow-Origin' '*';                    # 处理预检请求时允许的源
  14.             add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
  15.             add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization';
  16.             add_header 'Access-Control-Max-Age' 1728000;
  17.             add_header 'Content-Type' 'text/plain; charset=UTF-8';
  18.             add_header 'Content-Length' 0;
  19.             return 204;                                                     # 针对OPTIONS请求返回204 No Content
  20.         }

  21.         # 你的其他代理配置或静态文件配置,例如:
  22.         # proxy_pass http://backend-server;
  23.         # root /path/to/static/files;
  24.     }
  25. }
复制代码
只需截取location/{}段放进去
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|Discuz插件下载 ( 粤ICP备15082790号-1 )

GMT+8, 2025-9-1 10:02 , Processed in 0.045857 second(s), 16 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表