如何在nginx中启用CORS

时间:2018-06-01 04:35:06

标签: nginx cors

我卡住了,我不知道如何在CORS中启用nginx?老实说,我发现有很多解决方案可以在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 / {
    }

1 个答案:

答案 0 :(得分:2)

这绝对不是一个安全的解决方案...但这是我目前在设置中正在使用的方法,并且可以正常工作。也许您可以根据需要进行修改。让每个人都告诉我这是怎么回事,也许我们可以为每个人提供更好的解决方案。

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