反向代理适用于很多场合,负载均衡是最普遍的用法。

nginx 作为目前最流行的web服务器之一,可以很方便地实现反向代理。

nginx 反向代理官方文档: NGINX REVERSE PROXY

当在一台主机上部署了多个不同的web服务器,并且需要能在80端口同时访问这些web服务器时,可以使用 nginx 的反向代理功能: 用 nginx在80端口监听所有请求,并依据转发规则(比较常见的是以 URI 来转发)转发到对应的web服务器上。

例如有 webmail , webcom 以及 webdefault 三个服务器分别运行在 portmail , portcom , portdefault 端口,要实现从80端口同时访问这三个web服务器,则可以在80端口运行 nginx, 然后将 /mail 下的请求转发到 webmail 服务器, 将 /com下的请求转发到 webcom 服务器, 将其他所有请求转发到 webdefault 服务器。

假设服务器域名为example.com,则对应的 nginx http配置如下:

http {
    server {
            server_name example.com;

            location /mail/ {
                    proxy_pass http://example.com:protmail/;
            }

            location /com/ {
                    proxy_pass http://example.com:portcom/main/;
            }

            location / {
                    proxy_pass http://example.com:portdefault;
            }
    }
}
  • 以上的配置会按以下规则转发请求( GET 和 POST 请求都会转发):
  • 将 http://example.com/mail/ 下的请求转发到 http://example.com:portmail/
  • 将 http://example.com/com/ 下的请求转发到 http://example.com:portcom/main/
  • 将其它所有请求转发到 http://example.com:portdefault/

需要注意的是,在以上的配置中,webdefault 的代理服务器设置是没有指定URI的,而 webmail 和 webcom 的代理服务器设置是指定了URI的(分别为 / 和 /main/)。 
如果代理服务器地址中是带有URI的,此URI会替换掉 location 所匹配的URI部分。 
而如果代理服务器地址中是不带有URI的,则会用完整的请求URL来转发到代理服务器。

官方文档描述:

If the URI is specified along with the address, it replaces the part of the request URI that matches the location parameter. 
If the address is specified without a URI, or it is not possible to determine the part of URI to be replaced, the full request URI is passed (possibly, modified).

以上配置的转发示例:

  • http://example.com/mail/index.html -> http://example.com:portmail/index.html
  • http://example.com/com/index.html -> http://example.com:portcom/main/index.html
  • http://example.com/mail/static/a.jpg -> http://example.com:portmail/static/a.jpg
  • http://example.com/com/static/b.css -> http://example.com:portcom/main/static/b.css
  • http://example.com/other/index.htm -> http://example.com:portdefault/other/index.htm

 

==============================================================

前后端分离,转发请求到Tomcat的尝试

一、谈谈“渲染”

相信好多人都挺听过“渲染”这个词,但不清楚它是什么意思?前端开发以为这是后端的活儿,后端开发以为是前端的事儿,推着推着就不了了之。其实渲染很简单,不说概念,直接举例:

1、 后端渲染:以JSP为例,可以分成三步
a、编写标签或Java代码(可以称之为模板)
b、在JSP编译阶段被转换成Servlet编译为Servlet Class
c、执行编译后的代码,将响应(模板执行结果)返回给页面

优势:减少前端工作,前端只需要设计纯页面,其他的都由后端来做;

缺点:依赖于服务器端,增大服务器压力,前后端职责分工不明确;

应用场景:在页面不太多、渲染压力不大、服务器端能够承受范围内可以使用后端渲染。

2、 前端渲染:以基于JS的模板引擎为例
a、编写模板代码
b、通过模板引擎将模板转化为脚本语言,拼接在JS中(第一次拼接,以后使用缓存)
c、页面加载执行JS

优势:减少服务器压力,前后端职责可以很好地分开,后端只做Json数据接口,前端进行渲染;

缺点:前端渲染依赖于客户端,增大的前端压力,需要代理服务器、末班渲染引擎的支持;

应用场景:在前端页面较多,前端开发人员能力较强,需要前后端分离的场景可以使用前端渲染(前端渲染是趋势)。

 二、谈谈nginx

1、谈谈为什么会用到nginx?

首先明确一件事,浏览器可以发出请求吗?可以!那我们为什么要用到服务器呢?因为我们的前端如果不依赖服务器,页面就只能访问本地资源而不能访问服务器上的资源,而我们的后台一定是写在服务器上的。所以举个例子,我们在使用Tomcat服务器时,就必须把前端资源架在Tomcat上,才能访问后台的servlet。如下图所示:

nginx配置转发到java后端 nginx如何转发请求_运维

所以当我们希望前后端分离时,前端的资源就不能放在Tomcat上面,那如何获得Tomcat的资源的?这就用到了nginx,如下图所示:

nginx配置转发到java后端 nginx如何转发请求_后端_02

2、谈谈nginx的反向代理

有反向代理必有正向代理,先谈谈正向代理:一般默认的代理都是正向代理,用户访问不了一个资源,然后通过代理服务器去访问这个资源,将响应带回给用户。关键在于用户知道自己访问的是其他服务器的资源,代理服务器不会掩饰URL

反向代理是,代理服务器也是在中间层,但是用户不知道自己访问的资源是其他服务器的资源,代理服务器会掩饰URL

 

3、谈谈如何使用nginx反向代理tomcat

(1)首先打开nginx,两种方式,一种是直接点击ngnix.exe,一种是使用命令行,cd到nginx目录下,start nginx,无报错即启动成功

nginx配置转发到java后端 nginx如何转发请求_后端_03

 

(2)启动成功后,如何验证,因为ngnix.conf核心配置文件默认配置监听80端口,所以浏览器打开localhost,看到如下显示:

nginx配置转发到java后端 nginx如何转发请求_nginx配置转发到java后端_04

 

(3)下一步就是配置反向代理Tomcat,打开conf目录下的nginx.conf文件,主要看35行左右开始的代码,下面是我修改过的代码:

主要修改lacation属性,使所有的请求都被转发到http://localhost:8080的Tomcat服务器下处理:

nginx配置转发到java后端 nginx如何转发请求_nginx配置转发到java后端_05

listen:是监听的端口,即用户访问nginx服务的端口

server_name:服务名,经过测试并不会影响到什么

location:定义资源类型与服务器中资源地址url的映射关系,可在/后面定义资源类型,可设置多个location

其中proxy_pass代表要反向代理的服务器资源url,只要资源类型匹配,在这个url下的子路径资源都可以访问到,

其中root代表本地的资源路径,同样只要资源类型匹配,这个路径下的子目录资源都可以被访问到,

一个location中只能配置一个root或proxy_pass。

 

(4)修改后ngnix.conf文件后,使用nginx -s reload指令,重启ngnix,如果没有报错即重启成功

nginx配置转发到java后端 nginx如何转发请求_nginx配置转发到java后端_06

 

(5)发出请求,获得Json,url显示依然是80端口的资源,即我们说的反向代理的特点,掩饰url,效果如下图所示:

nginx配置转发到java后端 nginx如何转发请求_运维_07

事实上,nginx是将请求转发到Tomcat服务器,是8080端口下的资源,如下图所示:

nginx配置转发到java后端 nginx如何转发请求_运维_08

(6)如果不光有Tomcat服务器的资源,那么就需要定义多个location,比如,jsp资源请求就转发到Tomcat服务器下,php、html、js、css等资源资源可以转到Apache服务器目录下,如下图配置示例:

location ~ \.jsp$ {  
        proxy_pass http://localhost:8080;  
}  
          
location ~ \.(html|js|css|png|gif)$ {  
    root D:/software/developerTools/server/apache-tomcat-7.0.8/webapps/ROOT;  
}

配置例子:

upstream agent {
         #ip_hash;
         server 10.25.84.250:7072 weight=1 max_fails=2 fail_timeout=30s;
         server 10.25.84.250:7082 weight=1 max_fails=2 fail_timeout=30s;
    }
    
    upstream api {
         ip_hash;
         server 10.25.84.250:7070 weight=1 max_fails=2 fail_timeout=30s;
         #server 10.25.84.250:7080 weight=1 max_fails=2 fail_timeout=30s;
    }

    upstream admin {
         server 10.25.84.250:7073;
    }

    upstream websocket {
        server 10.25.84.250:7073;
    }
	
	upstream histps {
        ip_hash;
        server 10.25.84.233:8083 weight=1 max_fails=2 fail_timeout=30s;
    }
 
    server {
        listen       80;
        server_name  localhost;

        location ~ ^/websocket/.*$ {
            proxy_pass http://websocket;
                        proxy_http_version 1.1;
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection "Upgrade";
                        rewrite  /websocket/(.*)$ /$1 break;
        }

        location ~ ^/hiap-admin/.*\.do$ {
	     rewrite      /hiap-admin/(.*)$ /$1 break;
             proxy_next_upstream http_502 http_504 error timeout invalid_header;
             proxy_set_header Host  $host;
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_pass http://admin;
             expires      3d;
        }

	location ~ ^/hiap-api/.*\.do$ {
	     rewrite      /hiap-api/(.*)$ /$1 break;
             proxy_next_upstream http_502 http_504 error timeout invalid_header;
             proxy_set_header Host  $host;
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_pass http://api;
             expires      3d;
        }
        
        location ~ ^/hiap-agent/.*\.do$ {
	     rewrite      /hiap-agent/(.*)$ /$1 break;
             proxy_next_upstream http_502 http_504 error timeout invalid_header;
             proxy_set_header Host  $host;
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_pass http://agent;
             expires      3d;
        }
	
        location /hiap-admin {
            alias /mnt/www/hiap-admin-h5;
            index pandora_index.html;
        }
		
		location /his-tps {  
            proxy_pass http://histps/his-tps;  
            proxy_set_header Host $host;  
        }
    }

	
	upstream histpaportal {  
		ip_hash;
		server 30.4.136.224:8282;  
		server 30.4.137.116:8282;
	}
	upstream hiscas {  
		#  ip_hash;
        server 30.4.136.179:44911 max_fails=2 fail_timeout=5s;;
        server 30.4.136.180:44911 max_fails=2 fail_timeout=5s;;
        sticky;      #ip_hash可能负载不均衡。改成sticyk会话保持
   
	}
	server {  
		   listen       ???  
		   server_name  ???  
		   proxy_set_header Host $http_host;  
		   proxy_set_header x-forwarded-for  $remote_addr;  
		   proxy_buffer_size         64k;  
		   proxy_buffers             32 64k;  
		   charset utf-8;  

		   access_log  logs/host.access.log  main;  
		   location = /50x.html {  
				  root   html;  
		   }  
			  
		location /portal {  
			proxy_pass http://histpaportal;  
			proxy_set_header Host $proxy_host;  
		}

		location /cas {  
			proxy_pass http://hiscas/cas;  
			proxy_set_header Host $proxy_host;  
		} 
	}

-----------------------------------------------------------------------------------------------------------------------------------------------

user  root;
 worker_processes  1;#error_log  logs/error.log;
 #error_log  logs/error.log  notice;
 #error_log  logs/error.log  info;#pid        logs/nginx.pid;
 events {
     worker_connections  1024;
 } http {
     include       mime.types;
     default_type  application/octet-stream;
     client_max_body_size 5m;    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
     #                  '$status $body_bytes_sent "$http_referer" '
     #                  '"$http_user_agent" "$http_x_forwarded_for"';    #access_log  logs/access.log  main;
    sendfile        on;
     #tcp_nopush     on;    #keepalive_timeout  0;
     keepalive_timeout  65;    #gzip  on;
    upstream mhis_audit_gateway {
         server 10.25.84.250:8181 max_fails=2 fail_timeout=5s;
         #server 10.25.84.250:8082 max_fails=2 fail_timeout=5s;
         #sticky;
     }
   
     server {
         listen       80;
         server_name  localhost;        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location /mhis-audit {
             proxy_set_header Host $host;
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_pass http://mhis_audit_gateway;
         }        location /zuul/mhis-audit {
             proxy_set_header Host $host;
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_pass http://mhis_audit_gateway;
         }        # location /mhis-audit/ {
         #    proxy_set_header Host $host;
         #    proxy_set_header X-Real-IP $remote_addr;
         #    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         #    proxy_pass http://mhis_audit_gateway;
         #}        location /audit/service {
             root   /wls/audit/html;
             index  index.html index.htm;
         }
   
         location /audit {
             root   /wls/audit/html;
             index  index.html index.htm;
         }        location / {
             root   /wls/audit/html/audit;
             index  index.html index.htm;
         }        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
         #
         #error_page   500 502 503 504  /50x.html;
         #location = /50x.html {
         #    root   html;
         #}        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
         #
         #location ~ \.php$ {
         #    proxy_pass   http://127.0.0.1;
         #}        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
         #
         #location ~ \.php$ {
         #    root           html;
         #    fastcgi_pass   127.0.0.1:9000;
         #    fastcgi_index  index.php;
         #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
         #    include        fastcgi_params;
         #}        # deny access to .htaccess files, if Apache's document root
         # concurs with nginx's one
         #
         #location ~ /\.ht {
         #    deny  all;
         #}
     }     # another virtual host using mix of IP-, name-, and port-based configuration
     #
     #server {
     #    listen       8000;
     #    listen       somename:8080;
     #    server_name  somename  alias  another.alias;    #    location / {
     #        root   html;
     #        index  index.html index.htm;
     #    }
     #}     # HTTPS server
     #
     #server {
     #    listen       443 ssl;
     #    server_name  localhost;    #    ssl_certificate      cert.pem;
     #    ssl_certificate_key  cert.key;    #    ssl_session_cache    shared:SSL:1m;
     #    ssl_session_timeout  5m;    #    ssl_ciphers  HIGH:!aNULL:!MD5;
     #    ssl_prefer_server_ciphers  on;    #    location / {
     #        root   html;
     #        index  index.html index.htm;
     #    }
     #}}

--------------------------------------------------------------------------------------------------------------------------------------

user  root;
 worker_processes  1;#error_log  logs/error.log;
 #error_log  logs/error.log  notice;
 #error_log  logs/error.log  info;#pid        logs/nginx.pid;
 events {
     worker_connections  1024;
 } http {
     include       mime.types;
     default_type  application/octet-stream;    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
     #                  '$status $body_bytes_sent "$http_referer" '
     #                  '"$http_user_agent" "$http_x_forwarded_for"';    #access_log  logs/access.log  main;
    sendfile        off;
     #tcp_nopush     on;    #keepalive_timeout  0;
     keepalive_timeout  65;    #gzip  on;
         
     upstream micp-portal {
         server 30.23.10.95:8282 max_fails=2 fail_timeout=5s;
     }    server {
         listen       80;
         server_name  localhost;
         client_max_body_size   5m;        #charset koi8-r;
        #access_log  logs/host.access.log  main;
                 
         location / {
             root /usr/local/nginx/html/micp;
             index index.html index.htm;            
         }        location ~(project.config.js) {
             root /usr/local/nginx/html/micp;
             add_header Cache-Control no-store;
             add_header Pragma no-cache;
         }        location ~(index.html) {
             root /usr/local/nginx/html/micp;
             add_header Cache-Control no-store;
             add_header Pragma no-cache;
         }        location ^~/micp- {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://micp-portal;
         }
         
         location /mhis-mis-screen {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://micp-portal;
         }         location /WebReport {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://micp-portal;
         }  
         
         location /fwa-query {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://micp-portal;
         } 
         
         location /libra-sdp{
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://micp-portal;
         }  
         location /lssapp {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://micp-portal;
         }         #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
         #
         error_page   500 502 503 504  /50x.html;
         location = /50x.html {
             root   html;
         }        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
         #
         #location ~ \.php$ {
         #    proxy_pass   http://127.0.0.1;
         #}        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
         #
         #location ~ \.php$ {
         #    root           html;
         #    fastcgi_pass   127.0.0.1:9000;
         #    fastcgi_index  index.php;
         #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
         #    include        fastcgi_params;
         #}        # deny access to .htaccess files, if Apache's document root
         # concurs with nginx's one
         #
         #location ~ /\.ht {
         #    deny  all;
         #}
     }     # another virtual host using mix of IP-, name-, and port-based configuration
     #
     #server {
     #    listen       8000;
     #    listen       somename:8080;
     #    server_name  somename  alias  another.alias;    #    location / {
     #        root   html;
     #        index  index.html index.htm;
     #    }
     #}     # HTTPS server
     #
     #server {
     #    listen       443 ssl;
     #    server_name  localhost;    #    ssl_certificate      cert.pem;
     #    ssl_certificate_key  cert.key;    #    ssl_session_cache    shared:SSL:1m;
     #    ssl_session_timeout  5m;    #    ssl_ciphers  HIGH:!aNULL:!MD5;
     #    ssl_prefer_server_ciphers  on;    #    location / {
     #        root   html;
     #        index  index.html index.htm;
     #    }
     #}}