nginx跨域转发配置
时间: 2023-09-03 22:12:44 浏览: 117
下面是一种基本的nginx配置,用于实现跨域转发:
```
location /api {
add_header 'Access-Control-Allow-Origin' '*';
proxy_pass http://backend_server:8080;
}
location / {
add_header 'Access-Control-Allow-Origin' '$http_origin';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
if ($request_method = 'OPTIONS') {
return 204;
}
}
```
这个配置中,通过在`/api`位置设置`add_header 'Access-Control-Allow-Origin' '*'`,实现了允许所有来源('*')的跨域访问。然后使用`proxy_pass`指令将请求转发到后端服务器的端口8080。当前端应用程序发送HTTP请求到`/api`位置时,Nginx会将请求转发到指定的后端服务器,并将响应返回给前端应用程序。这样就实现了通过Nginx代理转发配置来实现跨域访问。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [nginx实现跨域转发](https://blog.csdn.net/zwhfyy/article/details/130564300)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [通过Nginx代理转发配置实现跨域的方法(API代理转发)](https://download.csdn.net/download/weixin_38621082/12899025)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文