如何在 Nginx 中启用 CORS

如何在 Nginx 中启用 CORS

我尝试了互联网上和 serverfault 上关于此问题的所有教程。无论我做什么,CORS 都无法在 nginx 中工作

这是我的 example.conf

服务器 {
        根目录/var/www/html;
        索引 index.php index.html index.htm index.nginx-debian.html;
        服务器名称 www.arcadesite.io arcadesite.io;

    location = /favicon.ico { log_not_found off; access_log off; }
location = /robots.txt { log_not_found off; access_log off; allow all; }
location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
    expires max;
    log_not_found off;
}


    location / {
            try_files $uri $uri/ /index.php$is_args$args;
            add_header Access-Control-Allow-Origin *;
     }

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }

    location ~ /\.ht {
            deny all;
    }

    location ~* \.(eot|ttf|woff|woff2)$ {
    add_header Access-Control-Allow-Origin *;
    }


listen 443 ssl http2;
ssl_certificate /etc/letsencrypt/live/arcadesite.io/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/arcadesite.io/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

包括 rocket-nginx/default.conf;

} 服务器 { 如果 ($host = www.arcadesite.io) { 返回 301 https://$host$request_uri; }

if ($host = arcadesite.io) { return 301 https://$host$request_uri; } listen 80; server_name www.arcadesite.io arcadesite.io; return 404;include rocket-nginx/default.conf;}

答案1

尝试添加这段代码location:

 if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        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';
     }

相关内容