Nginx 极简教程,常用场景统统解析( 四 )


前端和后端如果使用 http 进行交互时 , 请求会被拒绝 , 因为存在跨域问题 。来看看 , nginx 是怎么解决的吧:
首先 , 在 enable-cors.conf 文件中设置 cors :
# allow origin listset $ACAO '*';# set single originif ($http_origin ~* (www.helloworld.com)$) {set $ACAO $http_origin;}if ($cors = "trueget") { add_header 'Access-Control-Allow-Origin' "$http_origin"; add_header 'Access-Control-Allow-Credentials' 'true'; 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') {set $cors "${cors}options";}if ($request_method = 'GET') {set $cors "${cors}get";}if ($request_method = 'POST') {set $cors "${cors}post";}接下来 , 在你的服务器中 include enable-cors.conf 来引入跨域配置:
# ----------------------------------------------------# 此文件为项目 nginx 配置片段# 可以直接在 nginx config 中 include(推荐)# 或者 copy 到现有 nginx 中 , 自行配置# www.helloworld.com 域名需配合 dns hosts 进行配置# 其中 , api 开启了 cors , 需配合本目录下另一份配置文件# ----------------------------------------------------upstream front_server{server www.helloworld.com:9000;}upstream api_server{server www.helloworld.com:8080;}server {listen80;server_namewww.helloworld.com;location ~ ^/api/ {include enable-cors.conf;proxy_pass http://api_server;rewrite "^/api/(.*)$" /$1 break;}location ~ ^/ {proxy_pass http://front_server;}}到此 , 就完成了 。
作者:松华说
链接:https://juejin.im/post/5f027a20f265da22e93e4f43

【Nginx 极简教程,常用场景统统解析】


推荐阅读