如何在nginx中启用CORS

6
我遇到了一个问题,不知道如何在nginx中启用CORS。老实说,我找到了很多在nginx中启用CORS的解决方案,其中之一是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 / {
    }

请展示您的nginx.conf文件和请求。 - Alex C
@AlexC 我已经编辑了我的问题。 - PPShein
你忘记在允许方法中添加OPTIONS。 - VelikiiNehochuha
@AlexC 仍然无法工作。 - PPShein
@ppshein,请展示您的请求细节。 - Alex C
@AlexC 请尝试访问此网址 http://sanmel.wave.money/#/callback - PPShein
1个回答

6

这绝不是一个安全的解决方案......但这是我目前在我的设置中使用的,它正在工作。也许你可以根据自己的需要进行修改。欢迎大家告诉我它有多么错误,也许我们可以为每个人找到更好的解决方案。

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;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接