1. 程式人生 > >Nginx自學手冊(四)反向代理和緩存

Nginx自學手冊(四)反向代理和緩存

nginx proxy

(一)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:http, server, location

具體的實例如下:

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自學手冊(四)反向代理和緩存