前后端分离使用NGINX做服务转发

前言

前后端分离作为现在的大趋势,公司也开始了整合评估现有项目,打算对现有项目做前后端分离配置, 现阶段主要打算使用 NGINX 做前端静态的HTTP请求服务器,还包括对 WebSocket 内容的转发,当然还包括最主要的后台服务的负载均衡。

nginx配置

在nginx.conf中配置了 include /etc/nginx/sites-enabled 所以在 sites-enabled 下面编写配置信息.

map $http_upgrade $connection_upgrade {  
	default upgrade;  
	'' close;  
}  
upstream muti_instance_43{
#	server 192.168.10.62:9999 weight=10;
	server 192.168.10.62:9999;
#	server 192.168.10.213:9997 weight=2;
	keepalive 200;
}

server {
	listen 0.0.0.0:10070;
	sendfile off;


	proxy_set_header Host $http_host;
	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	proxy_set_header X-Forwarded-Proto $scheme;
#	resolver 114.114.114.114 223.5.5.5 valid=3600s;
        resolver_timeout 3s;

	proxy_http_version 1.1;
	proxy_set_header Connection "";

	#root /data/securityUI/static/;


	location  / { 
                #add_header 'Access-Control-Allow-Origin' '*';
		#add_header 'Access-Control-Allow-Methods' 'GET';
		#add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
		#add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
		#add_header 'Access-Control-Max-Age' 2592000;
		client_max_body_size    15g;
		#dav_access user:rw group:rw all:rw;
		#dav_methods PUT DELETE MKCOL COPY MOVE;

		#create_full_put_path on;

		#autoindex off;
		#autoindex_exact_size off;
		#autoindex_localtime on;
		#charset utf-8;
		if ($request_uri ~* /.) {
			proxy_pass http://muti_instance_43;
			break;
			#root /data/securityUI/static/;
                	#index index.html index.htm;
	
		}
		root /data/securityUI/static/;
                index login.html;
	}

	location ^~ /static/offlineMap/ {
		alias /data/securityUI/map/;
		#proxy_pass http://map_server;
	}

	location  /static/ {

		client_max_body_size 15g;
		alias /data/securityUI/static/;
		allow all;

	}
	location ^~ /index {
		alias /data/securityUI/static/;
		index index.html;

	}

	location ^~ /gee/ {
		proxy_pass http://muti_instance_43;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection "upgrade";
		proxy_http_version 1.1;
		proxy_set_header        Host            $host;
		proxy_set_header        X-Real-IP       $remote_addr;
		proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

	}
}

总结

配置中最关键的点在 location / {} 节点, 其中的 if 判断, 如果是访问的 ip:port/xxx 带了任何内容, 就会转发到 muti_instance_43 中, 如果没有带内容(即访问的首页), 就会将其转发到配置好了的静态首页面.