在前一讲中介绍了反向代理,我们知道:反向代理(Reverse Proxy)方式是指以代理服务器来接受 internet 上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给 internet 上请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器。这一讲就来做几个案例。

案例1:使用 nginx 反向代理 www.mytomcat.com 直接跳转到127.0.0.1:8080。

(1)环境准备

a.安装tomcat

解压tomcat:tar -zxvf apache-tomcat-9.0.26.tar.gz

进入到tomcat下的bin目录,之心./startup.sh。

查看tomcat进程:ps -ef | grep tomcat

nginx 反代svn nginx反代教程_nginx

b.安装jdk

解压openjdk:tar -zxvf openjdk-13_linux-x64_bin.tar.gz

查看所在路径:pwd

配置环境变量:gedit /etc/profile

JAVA_HOME=/java/jdk-13  
export JAVA_HOME  
  
PATH=$JAVA_HOME/bin:$PATH  
export PATH

使配置生效:source /etc/profile

查看是否安装成功:依次输入java、javac、java -version。

(2)进行反向代理

a.启动tomcat,ubuntu中浏览器地址栏访问,如下:

nginx 反代svn nginx反代教程_分布式_02

nginx 反代svn nginx反代教程_centos_03

b.查看虚拟机里Ubuntu的IP地址。

nginx 反代svn nginx反代教程_nginx_04

c.修改主机的host文件,将www.mytomcat.com映射到192.168.172.128。

路径:C:\Windows\System32\drivers\etc\hosts

加入信息:192.168.172.128 www.mytomcat.com

d.在虚拟机中修改nginx.conf文件信息。

#user  nobody;
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        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    server {
        listen       80;
        server_name  www.mytomcat.com;

        location / {
            proxy_pass http://127.0.0.1:8080;
            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;
    #    }
    #}

}

e.在真机的浏览器地址栏访问:http://www.mytomcat.com/,如下:

nginx 反代svn nginx反代教程_tomcat_05

案例2:使用Nginx反向代理,根据访问的不同路径跳转到不同端口的服务中。

(1)实现目标:

在真机地址栏访问http://192.168.172.128:9090/teacher/teacher.html,得到教师信息。

在真机地址栏访问http://192.168.172.128:9090/student/student.html,得到学生信息。

(2)实现过程

a.配置两个tomcat,其端口分别为8080和9090。

创建两个目录tomcat8080和tomcat9090,分别存放两个不同的tomcat。

nginx 反代svn nginx反代教程_分布式_06

复制tomcat的压缩包到创建的两个目录,并分别进行解压。

nginx 反代svn nginx反代教程_nginx_07

进入到tomcat9090的目录下,修改conf下的server.xml文件,将tomcat的配置端口改为9090。配置文件信息如下:

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="9015" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="9090" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the
         AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
    <!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="9019" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

b.分别启动两个tomcat,进行测试,保证修改成功。

nginx 反代svn nginx反代教程_分布式_08

nginx 反代svn nginx反代教程_分布式_09

c.进入到tomcat8080文件夹下,在webapps下创建teacher,并进入到teacher下创建teacher.html。

nginx 反代svn nginx反代教程_centos_10

nginx 反代svn nginx反代教程_tomcat_11

teacher.html内容如下:

<html>
<head>
    <title>教师信息</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
        .table{
            display:table;
            border-collapse:separate;
            border:1px solid #ccc;
			margin: 0 auto;
        }
        .table-caption{
            display:table-caption;
            margin:0;
            font-size:16px;
        }
        .table-header-group{
            display:table-header-group;
            background:#eee;
            font-weight:bold;
        }
        .table-row-group{
            display:table-row-group;
        }
        .table-footer-group{
            display:table-footer-group;
        }
        ul{
            list-style:none;
        }
        .table-row{
            display:table-row;
        }
        .table-cell{
            display:table-cell;
            padding:0 5px;
            border:1px solid #ccc;
        }
        .table-row-group .table-row:hover,
        .table-footer-group .table-row:hover{
            background:#f6f6f6;
            color:green;
            font-weight: bold;
        }
 
        .table-column-group{
            display:table-column-group;
        }
        .table-column{
            display:table-column;
            width:100px;
        }
    </style>
</head>
<body>
    <div class="table">
        <h2 class="table-caption">教师信息</h2>
        <!--此行代码用于,控制列的样式。-->
        <div class="table-column-group">
            <div class="table-column"></div>
            <div class="table-column"></div>
            <div class="table-column"></div>
        </div>
        <div class="table-header-group">
            <ul class="table-row">
                <li class="table-cell">序号</li>
                <li class="table-cell">姓名</li>
                <li class="table-cell">年龄</li>
            </ul>
        </div>
        <div class="table-row-group">
            <ul class="table-row">
                <li class="table-cell">1</li>
                <li class="table-cell">王健</li>
                <li class="table-cell">53</li>
            </ul>
            <ul class="table-row">
                <li class="table-cell">2</li>
                <li class="table-cell">刘倩</li>
                <li class="table-cell">32</li>
            </ul>
            <ul class="table-row">
                <li class="table-cell">3</li>
                <li class="table-cell">程晨</li>
                <li class="table-cell">39</li>
            </ul>
        </div>
        
    </div>
</body>

d.进入到tomcat9090文件夹下,在webapps下创建student,并进入到student下创建student.html。

nginx 反代svn nginx反代教程_tomcat_12

nginx 反代svn nginx反代教程_centos_13

student.html内容如下:

<html>
<head>
    <title>学生信息</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
        .table{
            display:table;
            border-collapse:separate;
            border:1px solid #ccc;
			margin: 0 auto;
        }
        .table-caption{
            display:table-caption;
            margin:0;
            font-size:16px;
        }
        .table-header-group{
            display:table-header-group;
            background:#eee;
            font-weight:bold;
        }
        .table-row-group{
            display:table-row-group;
        }
        .table-footer-group{
            display:table-footer-group;
        }
        ul{
            list-style:none;
        }
        .table-row{
            display:table-row;
        }
        .table-cell{
            display:table-cell;
            padding:0 5px;
            border:1px solid #ccc;
        }
        .table-row-group .table-row:hover,
        .table-footer-group .table-row:hover{
            background:#f6f6f6;
            color:green;
            font-weight: bold;
        }
 
        .table-column-group{
            display:table-column-group;
        }
        .table-column{
            display:table-column;
            width:100px;
        }
    </style>
</head>
<body>
    <div class="table">
        <h2 class="table-caption">学生信息</h2>
        <!--此行代码用于,控制列的样式。-->
        <div class="table-column-group">
            <div class="table-column"></div>
            <div class="table-column"></div>
            <div class="table-column"></div>
        </div>
        <div class="table-header-group">
            <ul class="table-row">
                <li class="table-cell">序号</li>
                <li class="table-cell">姓名</li>
                <li class="table-cell">年龄</li>
            </ul>
        </div>
        <div class="table-row-group">
            <ul class="table-row">
                <li class="table-cell">1</li>
                <li class="table-cell">张国正</li>
                <li class="table-cell">18</li>
            </ul>
            <ul class="table-row">
                <li class="table-cell">2</li>
                <li class="table-cell">李飞</li>
                <li class="table-cell">22</li>
            </ul>
            <ul class="table-row">
                <li class="table-cell">3</li>
                <li class="table-cell">高方</li>
                <li class="table-cell">19</li>
            </ul>
        </div>
        
    </div>
</body>

e.在虚拟机中分别启动两个tomcat服务器,进行测试。

nginx 反代svn nginx反代教程_nginx_14

f.在nginx的配置文件中添加反向代理。

server {
        listen       9090;
        server_name  192.168.172.128;

        location ~ /teacher/ {
            proxy_pass http://127.0.0.1:8080;
        }
        
        location ~ /student/ {
            proxy_pass http://127.0.0.1:9090;
        }
    }

g.进行测试。

在真机地址栏输入:http://192.168.172.128:9090/teacher/teacher.html

nginx 反代svn nginx反代教程_nginx 反代svn_15

在真机地址栏输入:http://192.168.172.128:9090/student/student.html

nginx 反代svn nginx反代教程_tomcat_16