如何在nginx中启用CORS

我卡住了,我不知道如何在nginx中启用CORS?老实说,我已经找到了很多在nginx中启用CORS的解决方案,其中一个是https://enable-cors.org/server_nginx.html,但我在/etc/nginx/nginx.conf中添加了这些代码并重新启动了nginx服务器.但我再次尝试了内部邮递员并跟随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中启用CORS - 代码日志