symfony 4、cors、localhost、nginx 的工作原理

symfony 4、cors、localhost、nginx 的工作原理

我有这样的 nginx 配置:

server {
    listen  127.0.0.1:80;
    server_name wtf;
    root /home/egor/PhpstormProjects/wtf/public/;
    client_max_body_size 32m;

    location / {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
     }
     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
     }
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;

        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        internal;
    }

    location ~ \.php$ {
        return 404;
    }

    error_log /home/egor/PhpstormProjects/wtf/logs/project_api_error.log;
    access_log /home/egor/PhpstormProjects/wtf/logs/project_api_access.log;
}

根据本手册添加了 /location 中的 add_headers :https://enable-cors.org/server_nginx.html

添加这些块后,任何 URL 都会出现 403 或 404 错误。我测试了一下,如果删除所有添加的块,只留下这样的块:

 if ($request_method = 'GET') {
 }

我仍然遇到相同的错误。如何正确地将 CORS 支持添加到我的配置中?

相关内容