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

时间:2023-10-03 23:08:56

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=$ 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 '*';
  return ;
} 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 '*';
} 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 '*';
}

}


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