1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > nginx配置反向代理解决前后端分离跨域问题

nginx配置反向代理解决前后端分离跨域问题

时间:2019-04-10 11:21:30

相关推荐

nginx配置反向代理解决前后端分离跨域问题

独角兽企业重金招聘Python工程师标准>>>

摘自《AngularJS深度剖析与最佳实践》P132

nginx配置文件如下:

server {listen 80;server_name your.domain.name;location / {# 把跟路径下的请求转发给前端工具链(如gulp)打开的开发服务器# 如果是产品环境,则使用root等指令配置为静态文件服务器proxy_pass http://localhost:5000/;}location /api/ {# 把 /api 路径下的请求转发给真正的后端服务器proxy_pass http://localhost:8080/service/;# 把host头传过去,后端服务程序将收到your.domain.name, 否则收到的是localhost:8080proxy_set_header Host $http_host;# 把cookie中的path部分从/api替换成/serviceproxy_cookie_path /api /service;# 把cookie的path部分从localhost:8080替换成your.domain.nameproxy_cookie_domain localhost:8080 your.domain.name }}

配置完成后重启nginx服务:

nginx -s reload

flying get√ 总是要拼了命继续努力

目前很多网站都是用前后端完全分离的模式实现,即:后端通过API提供数据,前端使用API获取数据并渲染。不过这样做会存在API跨域的问题,这里介绍一种通过Nginx配置解决跨域问题的方法。

Nginx整体配置如下:

upstream service {server 127.0.0.1:8080;}map $http_origin $cors_header {default "";"~^https?://localhost(:[0-9]+)?$" "$http_origin";}server {listen 80;server_name 127.0.0.1;access_log /var/log/nginx/access.log;error_log /var/log/nginx/error.log;location = /favicon.ico { deny all; error_log off; access_log off; log_not_found off; }location /api/ {if ($request_method = 'OPTIONS') {add_header 'Content-Length' 0 always;add_header 'Content-Type' 'text/plain charset=UTF-8' always;add_header 'Access-Control-Allow-Origin' '$cors_header' always;add_header 'Access-Control-Allow-Credentials' 'true' always;add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;add_header 'Access-Control-Allow-Headers' 'Origin,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Accept,Cookie,Set-Cookie, X-AUTH-USER, X-AUTH-TOKEN' always;return 200;}if ($request_method = 'POST') {add_header 'Access-Control-Allow-Origin' '$cors_header' always;add_header 'Access-Control-Allow-Credentials' 'true' always;add_header 'Access-Control-Allow-Headers' 'Origin,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Accept,Cookie,Set-Cookie, X-AUTH-USER, X-AUTH-TOKEN' always;add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;}if ($request_method = 'GET') {add_header 'Access-Control-Allow-Origin' '$cors_header' always;add_header 'Access-Control-Allow-Credentials' 'true' always;add_header 'Access-Control-Allow-Headers' 'Origin,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Accept,Cookie,Set-Cookie, X-AUTH-USER, X-AUTH-TOKEN' always;add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;}uwsgi_pass service;include uwsgi_params;}}

API路径配置中的 "X-AUTH-USER, X-AUTH-TOKEN",是API中传递的自定义HEADER,需要在 "Access-Control-Allow-Headers"中指明。其中,"map $http_origin $cors_header"将需要跨域的域名或者IP解析出来,方便后面的配置处理。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。