nginx - 如何在 nginx 中启用 CORS

标签 nginx cors

我被卡住了,我不知道如何启用 CORSnginx ?老实说,我找到了很多解决方案来启用 CORS在 nginx 中,其中之一是 https://enable-cors.org/server_nginx.html但我已将这些代码添加到我的 /etc/nginx/nginx.conf 中并重新启动 nginx服务器。但是我再次在 postman 内部尝试过,并且出现以下错误 nginx .

<html>
    <head>
        <title>405 Not Allowed</title>
    </head>
    <body bgcolor="white">
        <center>
            <h1>405 Not Allowed</h1>
        </center>
        <hr>
        <center>nginx/1.12.1</center>
    </body>
</html>

请让我知道如何修复它。谢谢。
server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  localhost;
    root         /var/www/test/app/;

    # Load configuration files for the default server block.
    include /etc/nginx/default/*.conf;

    add_header 'Access-Control-Allow-Origin' *;
    add_header 'Access-Control-Allow-Methods' 'GET, POST';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

    location / {
    }

最佳答案

这绝不是一个安全的解决方案......但这是我目前在我的设置中所拥有的并且正在运行。也许您可以根据需要对其进行修改。欢迎大家告诉我这是多么错误,也许我们可以为每个人找到更好的解决方案。

location / {

      dav_methods PUT DELETE MKCOL COPY MOVE;

      # Preflighted requestis
      if ($request_method = OPTIONS) {
        add_header "Access-Control-Allow-Origin" *;
        add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD, DELETE";
        add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
        return 200;
      }

      # CORS WHITELIST EVERYTHING
      # This is allowing everything because I am running
      # locally so there should be no security issues.
      if ($request_method = (GET|POST|OPTIONS|HEAD|DELETE)) {
        add_header "Access-Control-Allow-Origin" *;
        add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
      }

       try_files $uri $uri/ /index.php$is_args$args;
    }

关于nginx - 如何在 nginx 中启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50636154/

相关文章:

javascript - IE10 和图像/ Canvas 的跨域资源共享 (CORS) 问题

来自原点的 Angular 和 WebApi Cors 请求已被 CORS 策略阻止

django - X accel redirect 不下载文件

Docker-compose 来自守护进程 : manifest for nginx:1. 15-alphine 的错误响应未找到: list 未知: list 未知

ruby-on-rails - Firefox不支持HTTP “Content-Type” “application/octet-stream”

shell - 我用于启动 NGiNX 的 shell 脚本不工作

node.js - Socket.io 与 NGINX 和 http 2

c# - 正确理解具有相同主机/不同端口和安全性的 CORS

java - JSP 中 JSON Web 服务出现跨域错误?

asp.net - 将 cors 添加到 aspx web api 2 混合