【问题标题】:CORS error requesting php file on NGINX在 NGINX 上请求 php 文件的 CORS 错误
【发布时间】:2019-01-19 11:55:32
【问题描述】:

我正在向 NGINX 发出 POST 请求,但收到 CORS 错误:

无法加载https://knode.work/save.php:对预检的响应 请求未通过访问控制检查:否 'Access-Control-Allow-Origin' 标头出现在 请求的资源。原点'https://www.knode.io' 因此不允许访问。

在 NGINX 上,我在 /etc/nginx/sites-available/default 中有这个:

location / {
     # First attempt to serve request as file, then
     # as directory, then fall back to displaying a 404.
     try_files $uri $uri/ =404;

     add_header "Access-Control-Allow-Origin"  *;
  }

location ~ \.php$ {
     include snippets/fastcgi-php.conf;
     fastcgi_pass unix:/run/php/php7.0-fpm.sock;

     add_header "Access-Control-Allow-Origin"  *;

  }

更多信息:

  1. 我已经更新了 NGINX 配置文件。请通过https://gist.github.com/jxxcarlson/c17f9d89e06f5804170a0e44236b9d9a查看要点

  2. NGINX 未发回 Access-Control-Allow-Origin 标头:http://noteimages.s3.amazonaws.com/uploads/Screenshot%202018-08-13%2008.38.52.png

【问题讨论】:

  • 你确定调用在封闭的服务器块上匹配吗?很高兴看到您的其余配置,如果您可以分享的话。
  • 这很可能是错误的——我是新手。这是/etc/nginx/sites-available/default 的要点:gist.github.com/jxxcarlson/c17f9d89e06f5804170a0e44236b9d9a 非常感谢您查看此内容!
  • 我已经更新了nginx 配置以及上一条评论中的要点。还是没有变化。我认为问题是特定于对 *.php 文件的请求。网上对此有一些讨论,但到目前为止我还没有找到好的答案。
  • sites-available/default — 是用于 knode.work 还是 www.knode.io?
  • 那是 knode.work -- 带有 PHP 的 NGINX 服务器

标签: php nginx


【解决方案1】:

原来需要安装nginx-extras

apt-get install nginx-extras

然后使用more_set_headers 而不是add_headers 配置/etc/nginx/sites-enabled/default,如下面的清单所示。通过这些更改,不会出现 CORS 错误。

location ~ \.php$ {

    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;

    if ($request_method = 'OPTIONS') {
        more_set_headers 'Access-Control-Allow-Origin: $http_origin';
        more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE, HEAD';
        more_set_headers 'Access-Control-Max-Age: 1728000';
        more_set_headers 'Access-Control-Allow-Credentials: true';
        more_set_headers 'Access-Control-Allow-Headers: Origin,Content-Type,Accept,Authorization';
        more_set_headers 'Content-Type: text/plain; charset=UTF-8';
        more_set_headers 'Content-Length: 0';
        return 204;
    }

    location ~ /\.ht {
    deny all;
    }

}

【讨论】:

  • 为什么要配置 ($request_method = 'OPTIONS') { 如果他正在发送 POST?
猜你喜欢
  • 2021-12-23
  • 2021-02-04
  • 2020-08-28
  • 2021-11-02
  • 2020-06-06
  • 2014-10-04
  • 2014-05-26
  • 2014-07-29
  • 2018-04-17
相关资源
最近更新 更多