【英文】Nginx配置允许跨域

Preface

Enabling CORS (Cross-Origin Resource Sharing) in Nginx configuration.

Allowing Cross-Origin

1
2
3
4
5
6
7
8
9
10
11
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}

root html;
index index.html index.htm;
}
  • If reverse proxy is configured, the configuration of add_header fields needs to be placed before the configuration of the proxy_pass field.
1
2
3
4
5
6
7
8
9
10
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}

proxy_pass http://localhost;
}

Completion

References

CSDN - Niu Niu Blog
Tencent Cloud Developer Community - User 4919348