Nginx配置(linux)

1.nginx 常用的命令和配置文件

(1)启动命令

在/usr/local/nginx/sbin 目录下执行 ./nginx

(2)关闭命令

在/usr/local/nginx/sbin 目录下执行 ./nginx -s stop

(3)重新加载命令

在/usr/local/nginx/sbin 目录下执行 ./nginx -s reload

2 反向代理实例一

实现效果:使用 nginx 反向代理,访问 www .123 .com 直接跳转到 127.0.0.1:8080

2.1 准备工作

2.11 启动一个 tomcat,浏览器地址栏输入 127.0.0.1:8080,出现如下界面

2.12 linux系统中,在Tomcat安装文件夹下的bin目录下,用以下命令启动Tomcat

./startup.sh

 浏览器访问: 

 

 2.13 在 windows 系统中访问 linux 中 nginx,默认不能访问的,因为防火墙问题

(1)关闭防火墙

(2)开放访问的端口号,80 端口

注意:所有命令要切换到目录/nginx/sbin下执行

查看开放的端口号: firewall-cmd --list-all
设置开放的端口号:
firewall-cmd --add-service=http –permanent
firewall-cmd --add-port=80/tcp --permanent
重启防火墙: firewall-cmd --reload

 

 2.14 访问过程分析:

2.2 实现步骤

2.21 通过修改本地 host 文件,将 www. 123 .com 映射到 127.0.0.1

2.22 修改Nginx配置文件:

 启动Tomcat

 启动Nginx

 在浏览器端输入 www.123.com 结果如下:

 

反向代理实例二

3.1 实现效果

 使用 nginx 反向代理,根据访问的路径跳转到不同端口的服务中,nginx 监听端口为 9001
访问 http:// 192.168.17.129 :9001/edu/ 直接跳转到 127.0.0.1:808 0
访问 http:// 192.168.17.129 :9001/vod/ 直接跳转到 127.0.0.1:808 1

3.2 准备工作


3.2.1 准备两个 tomcat 服务器,一个 8080 端口,一个 8081 端

 停掉先前启动的Tomcat,然后分别在tomcat8080和tomcat8081文件夹中解压Tomcat压缩文件,tomcat8080文件夹中的Tomcat直接启动

 

 

之后进入tomcat8081文件夹中修改Tomcat配置文件

 

以下几个地方 

8081这里一定要改

 

 (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="8015" 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 -->
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->

  <!-- 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">
    <!--
    <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="8081" protocol="HTTP/1.1"
        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="8081" protocol="HTTP/1.1"
               connectionTimeout="20000"
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
    -->
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the AprLifecycleListener.
    -->
    <!--
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
         OpenSSL for TLS.
         configuration is used below.
    -->
    <!--
               maxThreads="150" SSLEnabled="true" >
        <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 protocol="AJP/1.3"
               address="::1"
               port="8019"
               redirectPort="8443" />
    -->

         every request.  The Engine implementation for Tomcat stand alone
         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">

      <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
         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 protocol="AJP/1.3"
               address="::1"
               port="8019"
               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

之后启动8081端口的Tomcat 

接下来可以测试一下两个端口号的Tomcat有没有启动成功:

 

 

3.2.2 创建文件夹和测试页面

在/usr/src/tomcat8080/apache-tomcat-8.5.79/webapps下创建edu文件夹,并在里面创建a.html文件保存

 

 

在/usr/src/tomcat8081/apache-tomcat-8.5.79/webapps下创建vod文件夹,并创建a.html文件保存

 

 

测试:

 

 

3.3 具体配置

找到 nginx 配置文件,进行反向代理配置

 

server {
        listen       9001;
        server_name  192.168.10.155;

        location ~ /edu/ {
            proxy_pass http://127.0.0.1:8080;
        }
        location ~ /vod/ {
            proxy_pass http://127.0.0.1:8081;
        }

    }

location 指令说明
该指令用于匹配 URL。 语法如下:


1、= :用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配,如果匹配成功,就停止继续向下搜索并立即处理该请求。 2、~:用于表示 uri 包含正则表达式,并且区分大小写。 3、~*:用于表示 uri 包含正则表达式,并且不区分大小写。 4、^~:用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location 块中的正则 uri 和请求字符串做匹配。 注意:如果 uri 包含正则表达式,则必须要有 ~ 或者 ~* 标识。

 

对外访问的端口号要包含9001,8080,8081

开启防火墙:service firewalld restart
查看开放的端口号:firewall-cmd --list-all
设置开放的端口号:
firewall-cmd --add-service=http –permanent
firewall-cmd --add-port=80/tcp --permanent
重启防火墙:firewall-cmd --reload

接下来重启Nginx

关闭:./nginx -s stop

启动:./nginx

 

 

3.2.3 最终测试:

分别访问:

http://192.168.10.155:8080/edu/a.html

http://192.168.10.155:8081/vod/a.html

成功!

4 负载均衡

4.1 实现效果    


1 )浏览器地址栏输入地址 http://http://192.168.10.155/edu/a.html ,负载均衡效果,平均 8080
和 8081 端口中


4.2 准备工作


1 )准备两台 tomcat 服务器,一台 8080 ,一台 8081
2 )在两台 tomcat 里面 webapps 目录中,创建名称是 edu 文件夹,在 edu 文件夹中创建
页面 a.html ,用于测试

 测试:

 

 


4.3  在 nginx 的配置文件中进行负载均衡的配置

    #gzip  on;
    upstream myserver{
        server 192.168.10.155:8080;
        server 192.168.10.155:8081;
    }
    server {
        listen       80;
        server_name  192.168.10.155;

        #charset koi8-r;
        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            proxy_pass http://myserver;
        }
    }

重启Nginx

 

 4.4 最终测试

成功! 

4.4  nginx 分配服务器策略


第一种 轮询(默认)
每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器 down 掉,能自动剔除。


第二种 weight
weigh t 代表权重默认为 1, 权重越高被分配的客户端越多


第三种 ip_hash
每个请求按访问 ip 的 hash 结果分配,这样每个访客固定访问一个后端服务器


第四种 fair (第三方
按后端服务器的响应时间来分配请求,响应时间短的优先分配。

5 动静分离

通过 location 指定不同的后缀名实现不同的请求转发。通过 expires 参数设置,可以使浏
览器缓存过期时间,减少与服务器之前的请求和流量。具体 Expires 定义:是给一个资源
设定一个过期时间,也就是说无需去 服务端验证,直接通过浏览器自身确认是否过期即可,
所以不会产生额外的流量。此种方法非常适合不经常变动的资源。(如果经常更新的文件,
不建议使用 Expires 来缓存),我这里设置 3d ,表示在这 3 天之内访问这个 URL ,发送一
个请求,比对服务器该文件最后更新时间没有变化,则不会从服务器抓取,返回状态码 304
如果有修改,则直接从服务器重新下载,返回状态码 200 。

 

5.1 准备工作

1 )在 liunx 系统中准备静态资源,用于进行访问

image文件夹放一张图片,www文件夹放html文件

 5.2 修改Nginx配置文件

 server {
          listen       80;
          server_name  192.168.10.155;
  
          #charset koi8-r;
          #access_log  logs/host.access.log  main;
  
          location /www/ {
              root   /data/;
              index  index.html index.htm;
          }   
          location /image/{
              root /data/;
              autoindex on;
          }
}

重启nginx 

 

5.3 最终测试:

http://192.168.10.155/image/1.jpg

http://192.168.10.155/www/a.html

 

 6 高可用

6.1 什么是 nginx 高可用

 1 )需要两台 nginx 服务器
2 )需要 keepalived
3 )需要虚拟 ip

6.2  配置高可用的准备工作

1 )需要两台服务器 192.168.10.155 和 192.168.10.41
2 )在两台服务器安装 nginx

LINUX安装nginx详细步骤_大蛇王的博客-CSDN博客_linux安装nginx
3 )在两台服务器安装 keepalived


6.3  在两台服务器安装 keepalived

1 )使用 yum 命令进行安装: yum install keepalived y

        查看版本: rpm -q -a keepalived


2 )安装之后,在 etc 里面生成目录 keepalived ,有文件 keepalived.con f

 

 


6.4 完成高可用配置(主从配置)(未配置成功)

1 )修改 /etc/keepalived/keepalivec.conf 配置文件

主:

global_defs {
  notification_email {
    acassen@firewall.loc
    failover@firewall.loc
    sysadmin@firewall.loc
  }
  notification_email_from Alexandre.Cassen@firewall.loc
  smtp_server 1 92.168.17.129
  smtp_connect_timeout 30
  router_id LVS_DEVEL
}

vrrp_script chk_http_port {
  script "/usr/local/src/nginx_check.sh"
  interval 2  #(检测脚本执行的间隔) 
  weight 2
}

vrrp_instance VI_1 {
  state MASTER # 备份服务器上将 MASTER 改为 BACKUP
  interface ens33 // 网卡
  virtual_router_id 51 # 主、备机的 virtual_router_id 必须相同
  priority 100 # 主、备机取不同的优先级,主机值较大,备份机值较小
  advert_int 1
  authentication {
    auth_type PASS
    auth_pass 1111
  }
  virtual_ipaddress {
    192.168.17.50 // VRRP H 虚拟地址
  }
}


 备:

global_defs {
  notification_email {
    acassen@firewall.loc
    failover@firewall.loc
    sysadmin@firewall.loc
  }
  notification_email_from Alexandre.Cassen@firewall.loc
  smtp_server 1 92.168.17.129
  smtp_connect_timeout 30
  router_id LVS_DEVEL
}

vrrp_script chk_http_port {
  script "/usr/local/src/nginx_check.sh"
  interval 2  #(检测脚本执行的间隔) 
  weight 2
}

vrrp_instance VI_1 {
  state BACKUP # 备份服务器上将 MASTER 改为 BACKUP
  interface ens33 // 网卡
  virtual_router_id 51 # 主、备机的 virtual_router_id 必须相同
  priority 90 # 主、备机取不同的优先级,主机值较大,备份机值较小
  advert_int 1
  authentication {
    auth_type PASS
    auth_pass 1111
  }
  virtual_ipaddress {
    192.168.17.50 // VRRP H 虚拟地址
  }
}


2 )在 /usr/local/src 添加检测脚本

#!/bin/bash
A=`ps -C nginx no header |wc -l`
if [ $A -eq 0 ];then
	/usr/local/nginx/sbin/nginx
	sleep 2
	if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
		killall keepalived
	fi
fi

3 )把两台服务器上 nginx 和 keepalived 启动
启动 nginx : ./nginx
启动 keepalived:  systemctl start keepalived.service

 

6.5 最终测试

1 )在浏览器地址栏输入 虚拟 ip 地址 192.168.91.199

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值