nginx怎么解决跨域
时间: 2023-11-22 07:48:45 浏览: 77
nginx跨域问题解决
使用nginx反向代理是一种简单的跨域方式,只需要修改nginx的配置即可解决跨域问题。具体步骤如下:
1. 在nginx的配置文件中添加以下内容:
```nginx
location /api {
proxy_pass http://example.com; # 将请求转发到目标服务器
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-Allow-Credentials true; # 允许携带cookie
}
```
2. 将请求转发到目标服务器,例如将`http://localhost:8080/api`的请求转发到`http://example.com`:
```nginx
location /api {
proxy_pass http://example.com;
}
```
3. 允许所有来源跨域访问:
```nginx
add_header Access-Control-Allow-Origin *;
```
4. 允许携带cookie:
```nginx
add_header Access-Control-Allow-Credentials true;
```
5. 允许的请求方法:
```nginx
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
```
6. 允许的请求头:
```nginx
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
```
阅读全文