【linux】nginx options 跨域问题 请求HTTP错误405 用于访问该页的HTTP动作未被许可 Method Not Allowed

JavaScript JS 跨域问题

HTTP 错误 405 - 用于访问该页的 HTTP 动作未被许可
HTTP 错误 405.0 - Method Not Allowed

Nginx 处理跨域问题、OPTIONS 方法的问题

Method = "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT" | extension-method
extension-method = token

解决办法:


在Nginx location 里加上如下代码可以解决js 请求跨域问题:

 location / {
        if (!-e $request_filename){
            rewrite  ^(.*)$  /index.php?s=$1  last;   break;
        }
        
        
        if ($request_method = 'OPTIONS') { 
          add_header Access-Control-Allow-Origin *; 
          add_header Access-Control-Allow-Credentials true; 
          add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; 
          add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; 
          return 200; 
        }


        if ($request_method = 'POST') {
          add_header 'Access-Control-Allow-Origin' *; 
          add_header 'Access-Control-Allow-Credentials' 'true'; 
          add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; 
          add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        }


        if ($request_method = 'GET') {
          add_header 'Access-Control-Allow-Origin' *; 
          add_header 'Access-Control-Allow-Credentials' 'true'; 
          add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; 
          add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        }

 }

 

注意,必须放在 location ... { ... }里面才能用if条件判断。

猜你喜欢

转载自www.cnblogs.com/richerdyoung/p/9272445.html