代码之家  ›  专栏  ›  技术社区  ›  PPShein

如何在nginx中启用cors

  •  3
  • PPShein  · 技术社区  · 7 年前

    我被困在我不知道如何启用 CORS 在里面 nginx ?老实说,我找到了很多解决方案 科斯 在nginx,其中一个是 https://enable-cors.org/server_nginx.html 但我已经在我的 /etc/nginx/nginx.conf 重新开始 恩吉克斯 服务器。但我在邮递员里面又试过了 恩吉克斯 .

    <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 / {
        }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Noah Gary    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;
        }