admin 发表于 2025-8-30 12:52:49

nginx服务器跨域设置

server {
    listen 80;
    server_name your-api-domain.com; # 替换为你的实际域名或IP

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

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

      # 你的其他代理配置或静态文件配置,例如:
      # proxy_pass http://backend-server;
      # root /path/to/static/files;
    }
}只需截取location/{}段放进去
页: [1]
查看完整版本: nginx服务器跨域设置