我正在尝试将CORS标头添加到我的Nginx服务器。我尝试了以下方法:
include mime.types;
server {
listen 80;
listen [::]:80;
server_name #domain;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name #domain;
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PATCH, PUT, DELETE, HEAD, OPTIONS';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header Strict-Transport-Security “max-age=15768000” always;
add_header 'Content-Length' 0;
return 204;
}
if ($request_method ~* '(POST|GET|PUT|PATCH|DELETE)') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PATCH, PUT, DELETE, HEAD, OPTIONS';
add_header Strict-Transport-Security “max-age=15768000” always;
}
proxy_pass http://localhost:3000;
}
ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
ssl_session_cache shared:SSL:5m;
ssl_session_timeout 1h;
}
但是,虽然GET和OPTIONS添加了标头,但其他方法却没有。 我看到只有在上一个级别没有头的情况下才添加标头,因此我尝试将它们全部设置在同一级别。 我在做错什么吗?