Nginx自学手册反向代理和缓存

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Nginx自学手册反向代理和缓存相关的知识,希望对你有一定的参考价值。

(一)nginx反向代理

  1. 什么是代理服务器 :代理服务器,客户机在发送请求时,不会直接发送给目的主机,而是先发送给代理服务器,代理服务接受客户机请求之后,再向主机发出,并接收目的主机返回的数据,存放在代理服务器的硬盘中,再发送给客户机。 

  2. 为什么要使用代理服务器 
    1)提高访问速度 
    由于目标主机返回的数据会存放在代理服务器的硬盘中,因此下一次客户再访问相同的站点数据时,会直接从代理服务器的硬盘中读取,起到了缓存的作用,尤其对于热门站点能明显提高请求速度。 
    2)防火墙作用 
    由于所有的客户机请求都必须通过代理服务器访问远程站点,因此可在代理服务器上设限,过滤某些不安全信息。 
    3)通过代理服务器访问不能访问的目标站点 
    互联网上有许多开发的代理服务器,客户机在访问受限时,可通过不受限的代理服务器访问目标站点,通俗说,我们使用的翻墙浏览器就是利用了代理服务器,虽然不能出国,但也可直接访问外网。

  3. 反向代理服务器架设在服务器端,通过缓冲经常被请求的页面来缓解服务器的工作量,将客户机请求转发给内部网络上的目标服务器;并将从服务器上得到的结果返回给Internet上请求连接的客户端,此时代理服务器与目标主机一起对外表现为一个服务器。

  4. 反向代理服务器架设在服务器端,通过缓冲经常被请求的页面来缓解服务器的工作量,将客户机请求转发给内部网络上的目标服务器;并将从服务器上得到的结果返回给Internet上请求连接的客户端,此时代理服务器与目标主机一起对外表现为一个服务器。 本文主要讲解nginx代理服务器。

Nginx中的ngx_http_proxy_module模块可以实现后端服务器的反向代理功能,这样就可以实现客户端请求的动静分离以及负载均衡功能。


 环境简介:

服务器名称IP地址备注
nginx服务器192.168.180.4

node1192.168.180.23
httpd服务器
node2192.168.180.9tomcat服务器

具体步骤:

1,node1(192.168.180.23)httpd服务器的配置

  1.1通过yum安装httpd服务器

[[email protected] ~]# yum install httpd
Loaded plugins: fastestmirror
base                                                                               | 3.6 kB  00:00:00     
extras                                                                             | 3.4 kB  00:00:00     
updates                                                                            | 3.4 kB  00:00:00     
Loading mirror speeds from cached hostfile
 * base: mirrors.163.com
 * extras: centos.ustc.edu.cn
 * updates: mirrors.163.com
Resolving Dependencies
--> Running transaction check
---> Package httpd.x86_64 0:2.4.6-45.el7.centos.4 will be installed
--> Processing Dependency: httpd-tools = 2.4.6-45.el7.centos.4 for package: httpd-2.4.6-45.el7.centos.4.x86_64
--> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-45.el7.centos.4.x86_64
--> Running transaction check
---> Package httpd-tools.x86_64 0:2.4.6-45.el7.centos.4 will be installed
---> Package mailcap.noarch 0:2.1.41-2.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
==========================================================================================================
 Package                 Arch               Version                             Repository           Size
==========================================================================================================
Installing:
 httpd                   x86_64             2.4.6-45.el7.centos.4               updates             2.7 M
Installing for dependencies:
 httpd-tools             x86_64             2.4.6-45.el7.centos.4               updates              84 k
 mailcap                 noarch             2.1.41-2.el7                        base                 31 k
Transaction Summary
==========================================================================================================
Install  1 Package (+2 Dependent packages)
Total download size: 2.8 M
Installed size: 9.6 M
Is this ok [y/d/N]: y
(1/3): mailcap-2.1.41-2.el7.noarch.rpm                                             |  31 kB  00:00:00     
(2/3): httpd-tools-2.4.6-45.el7.centos.4.x86_64.rpm                                |  84 kB  00:00:00     
(3/3): httpd-2.4.6-45.el7.centos.4.x86_64.rpm                                      | 2.7 MB  00:00:00     
----------------------------------------------------------------------------------------------------------
Total                                                                     3.4 MB/s | 2.8 MB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : mailcap-2.1.41-2.el7.noarch                                                            1/3 
  Installing : httpd-tools-2.4.6-45.el7.centos.4.x86_64                                               2/3 
  Installing : httpd-2.4.6-45.el7.centos.4.x86_64                                                     3/3 
  Verifying  : httpd-tools-2.4.6-45.el7.centos.4.x86_64                                               1/3 
  Verifying  : mailcap-2.1.41-2.el7.noarch                                                            2/3 
  Verifying  : httpd-2.4.6-45.el7.centos.4.x86_64                                                     3/3 
Installed:
  httpd.x86_64 0:2.4.6-45.el7.centos.4                                                                    
Dependency Installed:
  httpd-tools.x86_64 0:2.4.6-45.el7.centos.4                 mailcap.noarch 0:2.1.41-2.el7                
Complete

 1.2配置httpd服务器

[[email protected] ~]# vim /etc/httpd/conf/httpd.conf 
ServerRoot "/etc/httpd"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to 
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 8888
DocumentRoot "/var/www/html"

1.3给httpd服务器做一个定制页面

[[email protected] html]# mkdir -p /var/www/html
[[email protected] html]# vim /var/www/html/index.html
this is 192.168.180.23 httpd server

1.4重启下httpd服务,显示如下页面

[[email protected] html]# service httpd restart          
Redirecting to /bin/systemctl restart  httpd.service

技术分享

2.node2(192.168.180.9)tomcat服务器的配置

  2.1 解压tomcat

[[email protected] local]# ls  
apache-tomcat-7.0.63.tar.gz
[[email protected] local]# tar xf apache-tomcat-7.0.63.tar.gz 
[[email protected] local]# mv apache-tomcat-7.0.63 tomcat

  2.2创建编辑自定义路径

[[email protected] WEB-INF]# mkdir /var/www
[[email protected] WEB-INF]# vim /var/www/index.jsp
this is tomcat test index.jsp

  2.3编辑修改端口和自定义网页测试路径

[[email protected] local]# vim tomcat/conf/server.xml 
<?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="8805" 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" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- 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 (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8088" 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"
               redirectrt="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the BIO implementation that requires the JSSE
         style configuration. When using the APR/native implementation, the
         OpenSSL style configuration is required as described in the APR/native
         documentation -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8809" 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 &quot;%r&quot; %s %b" />
        
         <Context path="" docBase="/var/www" debug="0" reloadable="true" crossContext="true"/>
      </Host>
    </Engine>
  </Service>
</Server>

  2.4重启tomcat服务并访问

[[email protected] WEB-INF]# /usr/local/tomcat/bin/startup.sh 
Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:        /usr/java/jdk1.7.0_79/
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Tomcat started.

技术分享

3.nginx 服务器的配置

[[email protected] server]# vim server.conf 
server {
         listen    80;
         server_name  xn3.lqb.com;
        # root /html/xn3;
         location / {
        proxy_pass http://192.168.180.23:8888;
        proxy_set_header Host    $host;
        proxy_set_header X-Real-IP  $remote_addr;
                        }
         }
[[email protected] server]# /usr/local/nginx/sbin/nginx -s reload

技术分享

备注:

proxy_pass http://192.168.180.23:8888;   设置代理服务器

proxy_set_header Host    $host; 自定义客户端请求的首部的值

proxy_set_header X-Real-IP  $remote_addr;  自定义头部信息加入客户端IP

nginx官方文档:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass



(二)缓存

    当Nginx将客户端请求反向代理至后端服务器时,建立的是keep-alive连接;代理服务器与客户端,代理服务器与后端web server都建立长链,这会降低Nginx性能,所以这时候,proxy模块的缓存功能就派上用场了,代理服务器与客户端之间依旧保持长链,而代理服务器与后端web server之间请求结束后,代理服务器将内容缓存在本地,与后端不建立长链,大大节省了系统资源;同时,当客户端请求来时,代理服务器会直接去缓存中寻找并返回给客户端。代理服务器将缓存存在内存中,以key-value形式存储,value存储的是指向本地文件系统中存储的URL的哈希值。

nginx官方文档关于缓存

Syntax:proxy_cache zone | off;
Default:
proxy_cache off;
Context:httpserverlocation

具体的实例如下:

 1.创建自定义的缓存目录

[[email protected] server]# mkdir -pv /cache/nginx/
[[email protected] server]# chown -R appuser.appuser /cache/nginx/

 2.在配置文件的http段定义缓存目录

[[email protected] server]# vim /usr/local/nginx/conf/nginx.conf
proxy_cache_path  /cache/nginx  keys_zone=mycache:32m;

 3.在server或location段均可使用,本文在location段中使用

[[email protected] server]# vim server.conf                      
server {
         listen    80;
         server_name  xn3.lqb.com;
     location / {
        proxy_cache mycache;
        proxy_cache_valid 200 3h;
        proxy_cache_valid 301 302 10m;
        proxy_cache_valid all 1m;
        proxy_cache_use_stale error timeout http_500 http_502 http_503;
        proxy_pass http://192.168.180.9;
        proxy_set_header Host    $host;
        proxy_set_header X-Real-IP  $remote_addr;
                     }
                    }

4,请求后,缓存目录中出现缓存信息

[[email protected] server]# ll /cache/nginx/
总用量 4
-rw------- 1 appuser appuser 362 8月   8 16:57 af619c8ddbeaa235da85e6b4963a861b


备注:

proxy_cache_path /cache/nginx/ keys_zone=mycache:32m;

定义缓存在文件系统中的保存路径,定义key值在内存中的变量名与大小,其余诸多选项有默认配置,定义在哪个位置,就有哪些配置可使用缓存

 

proxy_cache mycache;

使用mycache缓存

 

proxy_cache_valid 200 3h;

以响应状态码定义缓存保存时长,可定义多个

 

proxy_cache_use_stale error timeout http_500 http_502 http_503;

定义在遇到什么情况下可以使用过期缓存响应客户端

一般来说,我们把缓存路径定义在http段,调用缓存根据具体情况配置。

nginx官方文档:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache

本文出自 “清风明月” 博客,请务必保留此出处http://liqingbiao.blog.51cto.com/3044896/1954551

以上是关于Nginx自学手册反向代理和缓存的主要内容,如果未能解决你的问题,请参考以下文章

Nginx反向代理和缓存杂记

初识nginx反向代理和缓存机制

初识nginx反向代理和缓存机制(简单实现)

centos7.4 搭建nginx反向缓存代理

编译安装nginx并实现反向代理负载均衡和缓存功能

编译安装nginx并实现反向代理负载均衡和缓存功能