账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Nginx如何配置跨域请求时包含cookie
    55
    0

    前端: front.foo.com
    后端: back.foo.com

    当前端通过ajax调用后端接口的时候 如果想把cookie传给后端 需要显式设置:

    xhrFields: { withCredentials: true },
    

    如下所示

    $.ajax({
    type: “post”,
    url: ‘http://back.foo.com/search’,
    contentType : “application/json;charset=utf-8”,
    dataType: “json”,
    xhrFields: { withCredentials: true },
    ...
    

    不知道前端能不能不用显式做此设置 直接通过Nginx来实现此目的 如在请求头中动态的添加:withCredentials: true

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 队友最靓 普通会员 1楼

      在Nginx中,可以使用CORS(Cross-Origin Resource Sharing)来处理跨域请求。CORS允许来自不同源的请求共享同一块资源,只有当源域名和请求头中包含的域相匹配时,服务器才会响应。

      要配置Nginx来包含cookie,可以按照以下步骤操作:

      1. 打开Nginx配置文件(通常是/etc/nginx/nginx.conf)。

      2. http部分,添加以下CORS设置:

      ```nginx http { # 设置允许哪些域名进行跨域请求 allow万事达卡.com;

      # 设置允许哪些域进行跨域请求的资源类型
      allow all;
      

      } ```

      1. server部分,添加以下内容来处理跨域请求:

      ```nginx server { listen 80; server_name example.com;

      # 设置响应头中包含的域,例如:
      location / {
          # 在这里设置要共享的资源,例如:cookie
          proxy_set_header Content-Type "text/plain";
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Host $host;
          proxy_pass http://example.com;
      }
      

      } ```

      1. 保存配置文件并重启Nginx服务以应用更改。

      注意:这个配置将允许所有域名进行跨域请求,但不包括特定的IP地址。如果需要允许特定IP地址的请求,可以将location /块中的proxy_pass http://example.com;修改为proxy_pass http://example.com:3000;

      另外,为了保护网站免受跨站脚本(XSS)攻击,Nginx还提供了安全的跨域资源共享(CORS)设置,可以使用以下设置:

      ```nginx http { # 设置允许哪些域进行跨域请求 allow万事达卡.com;

      # 设置允许哪些域进行跨域请求的资源类型
      allow all;
      

      }

      设置CORS安全设置

      proxy_set_header Content-Type "text/plain"; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_set_header X-XSS-Protection "1; mode=block"; proxy_pass http://example.com; ```

      这个配置将启用CORS安全设置,以防止跨站脚本攻击。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部