Nginx

Nginx 配置跨域-http请求方法OPTIONS

By karp 1554 Views 5 MIN READ 0 Comments

介绍下场景 前端ajax 请求接口 前 进行了 options 请求
后端php 认为 options 是post 请求 所有导致 重复请求问题.

解决方案 判断 options 请求就 返回206

两种方式解决

php

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
exit();
}

nginx

location / { 

    if ( $request_method = 'OPTIONS' ) { 
        add_header 'Access-Control-Allow-Origin' "$http_origin";
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,Content-Type';
        add_header 'Content-Length' 0;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        return 206;
    }   

    ....

使用nginx 比较靠谱

http OPTIONS解释

  1. 获取服务器支持的HTTP请求方法;也是黑客经常使用的方法。支持请求方法与http协议版本及web服务器配置有关
  2. 用来检查服务器的性能。例如:AJAX进行跨域请求时的预检,需要向另外一个域名的资源发送一个HTTP OPTIONS请求头,用以判断实际发送的请求是否安全。
  3. http返回正常状态码为206

本文由 karp 原创

采用 CC BY-NC-SA 4.0 协议进行许可

转载请注明出处:https://www.ikarp.top/index.php/archives/274.html

标签: nginx

0 评论