设置nginx 允许跨域访问
时间: 2024-04-07 14:26:48 浏览: 21
设置nginx允许跨域访问的方法如下[^1]:
1. 打开nginx的配置文件,一般位于`/etc/nginx/nginx.conf`或`/etc/nginx/conf.d/default.conf`。
2. 在`http`块中添加以下配置:
```shell
http {
...
server {
...
location / {
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';
if ($request_method = 'OPTIONS') {
add_header Access-Control-Max-Age 1728000;
add_header Content-Type 'text/plain charset=UTF-8';
add_header Content-Length 0; return 204;
}
}
...
}
...
}
```
3. 保存配置文件并重启nginx服务。
这样配置后,nginx会在响应头中添加`Access-Control-Allow-Origin`字段,允许所有来源的请求访问。同时,还会添加`Access-Control-Allow-Methods`和`Access-Control-Allow-Headers`字段,指定允许的请求方法和请求头。对于OPTIONS请求,nginx会返回204状态码,表示预检请求成功。