首页 > 其他 > 详细

Nginx学习笔记

时间:2018-07-02 21:16:27      阅读:213      评论:0      收藏:0      [点我收藏+]

1.   学习计划

1、nginx的安装

2、Nginx配置虚拟机

3、Nginx实现反向代理

4、Nginx实现负载均衡 

2.   nginx简介及应用场景

Nginx是一款高性能的http 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器。由俄罗斯的程序设计师Igor Sysoev所开发,官方测试nginx能够支支撑5万并发链接,并且cpu、内存等资源消耗却非常低,运行非常稳定。

1、http服务器。Nginx是一个http服务可以独立提供http服务。可以做网页静态服务器。【root】

2、虚拟主机。可以实现在一台服务器虚拟出多个网站。例如个人网站使用的虚拟主机。【一个server节点就是一个虚拟主机】

3、反向代理负载均衡。当网站的访问量达到一定程度后,单台服务器不能满足用户的请求时,需要用多台服务器集群可以使用nginx做反向代理。并且多台服务器可以平均分担负载,不会因为某台服务器负载高宕机而某台服务器闲置的情况。【upstream  proxy_pass】

3.   nginx安装

下载nginx:

官方网站:

http://nginx.org/

使用的版本是1.8.0版本。

 技术分享图片

 

Nginx提供的源码。

3.1. 要求的安装环境

1、需要安装gcc的环境。yum install gcc-c++

2、第三方的开发包。

  • PCRE

       PCRE(Perl Compatible Regular Expressions)是一个Perl库,包括 perl 兼容的正则表达式库。nginx的http模块使用pcre来解析正则表达式,所以需要在linux上安装pcre库。

  yum install -y pcre pcre-devel

注:pcre-devel是使用pcre开发的一个二次开发库。nginx也需要此库。

  • zlib

       zlib库提供了很多种压缩和解压缩的方式,nginx使用zlib对http包的内容进行gzip,所以需要在linux上安装zlib库。

  yum install -y zlib zlib-devel

 

  • openssl

       OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及SSL协议,并提供丰富的应用程序供测试或其它目的使用。

       nginx不仅支持http协议,还支持https(即在ssl协议上传输http),所以需要在linux安装openssl库。

  yum install -y openssl openssl-devel

 

3.2. 安装步骤

 

第一步:把nginx的源码包上传到linux系统

第二步:解压缩

[root@localhost ~]# tar zxf nginx-1.8.0.tar.gz

3.2.1. configure

第三步:使用configure命令创建一makeFile文件。

./configure 
--prefix=/usr/local/nginx 
--pid-path=/var/run/nginx/nginx.pid 
--lock-path=/var/lock/nginx.lock 
--error-log-path=/var/log/nginx/error.log 
--http-log-path=/var/log/nginx/access.log 
--with-http_gzip_static_module 
--http-client-body-temp-path=/var/temp/nginx/client 
--http-proxy-temp-path=/var/temp/nginx/proxy 
--http-fastcgi-temp-path=/var/temp/nginx/fastcgi 
--http-uwsgi-temp-path=/var/temp/nginx/uwsgi 
--http-scgi-temp-path=/var/temp/nginx/scgi

 

注意:启动nginx之前,上边将临时文件目录指定为/var/temp/nginx,需要在/var下创建temp及nginx目录

[root@localhost sbin]# mkdir /var/temp/nginx/client -p

 

3.2.2. make&make install

第四步:make

第五步:make install

 技术分享图片

 

 

3.3. 启动nginx

进入sbin目录,nginx的启动可以直接执行nginx的bin文件, 当nginx启动后,可以通过-s 参数来控制nginx

[root@localhost sbin]# ./nginx 
nginx -s reload     #重新加载配置文件
nginx -s reopen     #重新打开log文件
nginx -s stop       #快速关闭nginx服务
nginx -s quit       #优雅的关闭nginx服务,等待工作进程处理完所有的请求 

技术分享图片

3.4. 关闭nginx:

[root@localhost sbin]# ./nginx -s stop

 

推荐使用:

[root@localhost sbin]# ./nginx -s quit 

kill 进程号【正常关闭】

kill -9 进程号【暴力关闭】

3.5. 重启nginx:

1、先关闭后启动。

3.6. 刷新配置文件

2、修改了Nginx的配置文件后,在不用重启Nginx的时候,可以用如下命令刷新配置文件:

[root@localhost sbin]# ./nginx -s reload

 

Nginx重新加载配置文件的过程:主进程接受到加载信号后:

  • 首先会校验配置的语法,然后生效新的配置,
  • 如果成功,则主进程会启动新的工作进程,同时发送终止信号给旧的工作进程。
  • 否则主进程回退配置,继续工作。

在第二步,旧的工作进程收到终止信号后,会停止接收新的连接请求,知道所有现有的请求处理完,然后退出。

3.4. 访问nginx

 技术分享图片

默认是80端口。

注意:是否关闭防火墙。

3.5. 进程模型

Nginx进程模型:1个主进程,n个工作进程,主进程负责配置和工作进程的管理,实际的请求由工作进程进行处理。Nginx是基于事件驱动和多路复用的工作模型。

3.6. nginx.conf

nginx conf文件结构介绍以及相关配置:

 https://blog.csdn.net/anonymalias/article/details/50950910

3.6.1.  文件结构

nginx的配置由特定的标识符(指令符)分为多个不同的模块。 
指令符分为简单指令块指令

  • 简单指令格式:[name parameters;]
  • 块指令格式:和简单指令格式有一样的结构,但其结束标识符不是分号,而是大括号{},块指令内部可以包含simple directives 和block directives, 可以称块指令为上下文(e.g. events, http, server, location)

conf文件中,所有不属于块指令的简单指令都属于main上下文的,http块指令属于main上下文,server块指令http上下文。

...              #全局块

events {         #events块
   ...
}

http      #http块
{
    ...   #http全局块
    server        #server块
    { 
        ...       #server全局块
        location [PATTERN]   #location块
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全局块
}

 

  1、全局块:配置影响nginx全局的指令。一般有运行nginx服务器的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。

  2、events块:配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。

  3、http块:可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。

  4、server块:配置虚拟主机的相关参数,一个http中可以有多个server。

  5、location块:配置请求的路由,以及各种页面的处理情况。

 一个例子:

########### 每个指令必须有分号结束。#################
#user administrator administrators;  #配置用户或者组,默认为nobody nobody。
#worker_processes 2;  #允许生成的进程数,默认为1
#pid /nginx/pid/nginx.pid;   #指定nginx进程运行文件存放地址
error_log log/error.log debug;  #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
events {
    accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为on
    multi_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off
    #use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大连接数,默认为512
}
http {
    include       mime.types;   #文件扩展名与文件类型映射表
    default_type  application/octet-stream; #默认文件类型,默认为text/plain
    #access_log off; #取消服务日志    
    log_format myFormat $remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for; #自定义格式
    access_log log/access.log myFormat;  #combined为日志格式的默认值
    sendfile on;   #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
    sendfile_max_chunk 100k;  #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
    keepalive_timeout 65;  #连接超时时间,默认为75s,可以在http,server,location块。

    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #热备
    }
    error_page 404 https://www.baidu.com; #错误页
    server {
        keepalive_requests 120; #单连接请求上限次数。
        listen       4545;   #监听端口
        server_name  127.0.0.1;   #监听地址       
        location  ~*^.+$ {       #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
           #root path;  #根目录
           #index vv.txt;  #设置默认页
           proxy_pass  http://mysvr;  #请求转向mysvr 定义的服务器列表
           deny 127.0.0.1;  #拒绝的ip
           allow 172.18.5.54; #允许的ip           
        } 
    }
} 

 

3.6.2.  配置介绍

Nginx配置详解 https://www.cnblogs.com/knowledgesea/p/5175711.html

完整的基本配置文件如下:

技术分享图片
#运行用户
user www-data;  
#启动进程,通常设置成和cpu的数量相等
worker_processes 1;
 
#全局错误日志及PID文件
error_log /var/log/nginx/error.log;
pid    /var/run/nginx.pid;
 
#工作模式及连接数上限
events {
  use  epoll;       #epoll是多路复用IO(I/O Multiplexing)中的一种方式,但是仅用于linux2.6以上内核,可以大大提高nginx的性能
  worker_connections 1024;#单个后台worker process进程的最大并发链接数
  # multi_accept on; 
}
 
#设定http服务器,利用它的反向代理功能提供负载均衡支持
http {
   #设定mime类型,类型由mime.type文件定义
  include    /etc/nginx/mime.types;
  default_type application/octet-stream;
  #设定日志格式
  access_log  /var/log/nginx/access.log;
 
  #sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,
  #必须设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,以平衡磁盘与网络I/O处理速度,降低系统的uptime.
  sendfile    on;
  #tcp_nopush   on;
 
  #连接超时时间
  #keepalive_timeout 0;
  keepalive_timeout 65;
  tcp_nodelay    on;
   
  #开启gzip压缩
  gzip on;
  gzip_disable "MSIE [1-6]\.(?!.*SV1)";
 
  #设定请求缓冲
  client_header_buffer_size  1k;
  large_client_header_buffers 4 4k;
 
  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/sites-enabled/*;
 
  #设定负载均衡的服务器列表
   upstream mysvr {
  #weigth参数表示权值,权值越高被分配到的几率越大
  #本机上的Squid开启3128端口
  server 192.168.8.1:3128 weight=5;
  server 192.168.8.2:80 weight=1;
  server 192.168.8.3:80 weight=6;
  }
 
 
  server {
  #侦听80端口
    listen    80;
    #定义使用www.xx.com访问
    server_name www.xx.com;
 
    #设定本虚拟主机的访问日志
    access_log logs/www.xx.com.access.log main;
 
  #默认请求
  location / {
     root  /root;   #定义服务器的默认网站根目录位置
     index index.php index.html index.htm;  #定义首页索引文件的名称
 
     fastcgi_pass www.xx.com;
     fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name; 
     include /etc/nginx/fastcgi_params;
    }
 
  # 定义错误提示页面
  error_page  500 502 503 504 /50x.html; 
    location = /50x.html {
    root  /root;
  }
 
  #静态文件,nginx自己处理
  location ~ ^/(images|javascript|js|css|flash|media|static)/ {
    root /var/www/virtual/htdocs;
    #过期30天,静态文件不怎么更新,过期可以设大一点,如果频繁更新,则可以设置得小一点。
    expires 30d;
  }
  #PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.
  location ~ \.php$ {
    root /root;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /home/www/www$fastcgi_script_name;
    include fastcgi_params;
  }
  #设定查看Nginx状态的地址
  location /NginxStatus {
    stub_status      on;
    access_log       on;
    auth_basic       "NginxStatus";
    auth_basic_user_file conf/htpasswd;
  }
  #禁止访问 .htxxx 文件
  location ~ /\.ht {
    deny all;
  }
    
   }
}
View Code

 

以上是一些基本的配置,使用Nginx最大的好处就是负载均衡

如果要使用负载均衡的话,可以修改配置http节点如下:

技术分享图片
#设定http服务器,利用它的反向代理功能提供负载均衡支持
http {
   #设定mime类型,类型由mime.type文件定义
  include    /etc/nginx/mime.types;
  default_type application/octet-stream;
  #设定日志格式
  access_log  /var/log/nginx/access.log;
 
  #省略上文有的一些配置节点
 
  #。。。。。。。。。。
 
  #设定负载均衡的服务器列表
   upstream mysvr {
  #weigth参数表示权值,权值越高被分配到的几率越大
  server 192.168.8.1x:3128 weight=5;#本机上的Squid开启3128端口
  server 192.168.8.2x:80 weight=1;
  server 192.168.8.3x:80 weight=6;
  }
 
  upstream mysvr2 {
  #weigth参数表示权值,权值越高被分配到的几率越大
 
  server 192.168.8.x:80 weight=1;
  server 192.168.8.x:80 weight=6;
  }
 
  #第一个虚拟服务器
  server {
  #侦听192.168.8.x的80端口
    listen    80;
    server_name 192.168.8.x;
 
   #对aspx后缀的进行负载均衡请求
  location ~ .*\.aspx$ {
 
     root  /root;   #定义服务器的默认网站根目录位置
     index index.php index.html index.htm;  #定义首页索引文件的名称
 
     proxy_pass http://mysvr ;#请求转向mysvr 定义的服务器列表
 
     #以下是一些反向代理的配置可删除.
 
     proxy_redirect off;
 
     #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
     proxy_set_header Host $host;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     client_max_body_size 10m;  #允许客户端请求的最大单文件字节数
     client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,
     proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
     proxy_send_timeout 90;    #后端服务器数据回传时间(代理发送超时)
     proxy_read_timeout 90;     #连接成功后,后端服务器响应时间(代理接收超时)
     proxy_buffer_size 4k;       #设置代理服务器(nginx)保存用户头信息的缓冲区大小
     proxy_buffers 4 32k;        #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
     proxy_busy_buffers_size 64k;  #高负荷下缓冲大小(proxy_buffers*2)
     proxy_temp_file_write_size 64k; #设定缓存文件夹大小,大于这个值,将从upstream服务器传
 
    }
 
   }
}
View Code

 

3.6.2.1.  server指令

通常情况下,conf文件存在多个server块,一个server就是一个虚拟主机通过listen的端口(默认是80端口)和server_name进行区分, 对不同的请求提供不同的服务,如下:

server {
    listen      80;
    server_name a.example.org;
    ...
}

 

listen指令的参数:可以是ip, hostname, ip/hostname:port, port, UNIX-domain socket.例如:

listen 127.0.0.1:8000;listen 127.0.0.1;listen 8000;listen *:8000;listen localhost:8000;
listen unix:/var/run/nginx.sock;

 

server块内部的listen和server_name不能和其他server块的完全相同,否则启动加载配置的时候会出错:

当nginx决定了哪一个server处理客户端请求后,nginx会解析request header中URI(这里以及后面提到的大部分都是指相对URI),然后匹配server块中的location指令的参数,匹配规则下一节会介绍。例如下例:

server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }
}  

 

location块指令会用其参数与客户端请求的URI进行匹配,匹配的URI请求会被定向到root指令定义的特殊本地文件系统目录中重定向规则为:将URI添加到root参数后面,生成一个本地文件路径,即:root参数 + URI请求。这里示例参数”/”会匹配所有的请求,一般都会默认存在。示例定位后的目录为html/,默认是定位到安装目录的路径下的html/(相对路径)。这里location块指令内部的两个简单指令的含义是:

  • root 指定重定向后uri的资源查找路径,这里html为相对路径,相对于nginx的安装目录。
  • index 指定首页index文件的名称,可以配置多个,参数以空格分开,按配置顺序查找。

默认的在nginx安装目录下都会存在一个html目标,在我电脑中为:/usr/local/nginx-1.8.0/html, 然后里面存在默认的nignx的欢迎界面,例如我安装nginx后直接启动nginx bin文件,然后访问对应的域名就得到了如下的页面: 
技术分享图片 
如果有多个location指令块匹配到,nginx的选择策略是the longest prefix最长前缀匹配原则。 
例如,当上述的server中再增加一个location块,匹配参数为”/htdocs/”,重定向的资源路径为如下配置,

server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        location /htdocs {
            root   /home/anonymalias;
            index  index.html;
        }
}  

 

当访问http://anonymalias.oicp.net:8008/htdocs/,就会匹配到/home/anonymalias/htdocs/index.html

3.6.2.2.  location指令

nginx的location指令是配置的核心,用于匹配client请求uri的path部分,然后对不同的请求提供不同的静态内容,或者通过反向代理重定向到内部的server

对于client的request, nginx会进行预处理,nginx首先对采用 ’%XX’(uri采用%+十六进制格式用于在浏览器和插件中显示非标准的字母和字符) 格式文本编码的uri进行解码。然后处理path中的相对路径符号’.’和‘..’,然后对于含有两个及以上的’/’压缩成一个’/’。 这样处理完后会得到一个干净的path,然后会用这个path会在server的location指令的参数进行匹配。

location 语法:
    location [ = | ~ | ~* | ^~ ] uri { ... }
    location @name { ... }

 

location指令的参数

    • 可以是一个前缀字符串,参数修饰符分为: 
      • 无任何修饰符;
      • “=” 修饰符:定义一个精确匹配,匹配是精确匹配优先级最高;
      • “^~” 修饰符:对应的参数作为最长字符串匹配到后,不会继续去搜索参数为正则表达式的location
    • 也可以是一个正则表达式,参数修饰符分为: 
      • ”~” 修饰符: location参数部分大小写敏感
      • “~*” 修饰符:location参数部分大小写不敏感;
location ~* \.(gif|jpg|jpeg)$ {
    [ configuration A ]
}

location ~ \.(gif|jpg|jpeg)$ {
    [ configuration B ]
}

若请求URI为/images/a.JPG,只能匹配A。

location匹配的过程: 
1. 首先nginx会把request的uri在location正常字符串参数中匹配出符合的最长字符串,并保存这个结果; 
2. 如果最长前缀匹配结果前面有 ”^~”修饰符,那么停止继续搜索; 
3. 如果最长匹配结果前有”=”修饰符,也会停止继续搜索; 
4. 接下来,去匹配参数为正则表达式的所有location,根据location的配置顺序,在匹配到第一个正则表达式时,即停止搜索其他的正则表达式; 
所以如官网上的下例:

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

 

  • 当请求”/”时,匹配到A
  • 当请求”/index.html”,会匹配到B;
  • 当请求”documens/document.html”,会匹配到C;
  • 当请求”/images/1.gif”,会匹配到D;匹配流程:首先会匹配到D,由于D的location的参数含有修饰符”^~”,当匹配到D后,不会再搜索参数为正则表达式的location;
  • 当请求”/documents/1.jpg”,会匹配到E;匹配流程:首先会匹配到C,此时会保存C的匹配结果,然后继续搜索参数为正则的location,结果发现E匹配上了,那么会丢弃之前匹配到的C

4.   配置静态访问

关键配置root

Web server很重要一部分工作就是提供静态页面的访问(做http服务器,提供服务),例如images, html page。nginx可以通过不同的配置,根据request请求,从本地的目录(有root指定,当配置了proxy_pass代理时候,nginx将不再直接提供服务,而只做请求转发)提供不同的文件返回给客户端。 

打开安装目录下的nginx.conf文件,默认配置文件已经在http指令块中创建了一个空的server块,在nginx-1.8.0中的http块中已经创建了一个默认的server块。内容如下:

server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        } 
}  

5.   配置虚拟主机

就是在一台服务器启动多个网站。一个server就是一个虚拟主机。

如何区分不同的网站:

1、域名不同

2、端口不同

 

5.1. 通过端口区分不同虚拟机

Nginx的配置文件:

/usr/local/nginx/conf/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;

    #一个server节点就是一个虚拟主机
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
       #Html是nginx安装目录下的html目录(静态页面存放的位置,也可以使用绝对路径)
            root   html;
            index  index.html index.htm;
        }
    }
}

 

可以配置多个server,配置了多个虚拟主机。

 

添加虚拟主机:

#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;

    server {
        listen       80;
        server_name  localhost;(域名)

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        Location / {
            root   html;
            index  index.html index.htm;
        }
    }
    server {
        listen       81;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html-81;
            index  index.html index.htm;
        }
    }
}

 

重新加载配置文件

[root@localhost nginx]# sbin/nginx -s reload

 

 

5.2. 通过域名区分虚拟主机

5.2.1.    什么是域名

域名就是网站。

www.baidu.com

www.taobao.com

www.jd.com

Tcp/ip

 

Dns服务器:把域名解析为ip地址。保存的就是域名和ip的映射关系。

一级域名:

Baidu.com

Taobao.com

Jd.com

二级域名:

www.baidu.com

Image.baidu.com

Item.baidu.com

三级域名:

1.Image.baidu.com

Aaa.image.baidu.com

 

一个域名对应一个ip地址,一个ip地址可以被多个域名绑定。

 

本地测试可以修改hosts文件。

修改window的hosts文件:(C:\Windows\System32\drivers\etc)

可以配置域名和ip的映射关系,如果hosts文件中配置了域名和ip的对应关系,不需要走dns服务器。

 

 

5.2.2.    Nginx的配置

 

技术分享图片
#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;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
    }
    server {
        listen       81;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html-81;
            index  index.html index.htm;
        }
    }
    server {
        listen       80;
        server_name  www.taobao.com;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html-taobao;
            index  index.html index.htm;
        }
    }
    server {
        listen       80;
        server_name  www.baidu.com;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html-baidu;
            index  index.html index.htm;
        }
    }
}
View Code

 

域名的配置:

192.168.25.148 www.taobao.com

192.168.25.148 www.baidu.com

 

 

 

6.   反向代理

Nginx代理功能与负载均衡详解:

https://www.cnblogs.com/knowledgesea/p/5175711.html

http://www.cnblogs.com/knowledgesea/p/5199046.html

6.1. 什么是反向代理

正向代理

(代理客户端)接收到客户端,替代客户端去完成上网,将获得的结果返回给客户端。

 技术分享图片

反向代理:(代理服务端)

 技术分享图片

 

反向代理服务器决定哪台服务器提供服务

返回代理服务器不提供服务器。只是请求的转发。

Nginx在做反向代理时,提供性能稳定,并且能够提供配置灵活的转发功能Nginx可以根据不同的正则匹配,采取不同的转发策略,比如图片文件结尾的走文件服务器,动态页面走web服务器,只要你正则写的没问题,又有相对应的服务器解决方案,你就可以随心所欲的玩。并且Nginx对返回结果进行错误页跳转,异常判断等。如果被分发的服务器存在异常,他可以将请求重新转发给另外一台服务器,然后自动去除异常服务器。

下面是nginx官方最简单的一个proxy server的配置示例:

 

server {
    location / {
        proxy_pass http://localhost:8080/;
    }

    location ~ \.(gif|jpg|png)$ {
        root /data/images;
    }
}

 

配置的含义:所有URI中以.gif, .jpg, .png结尾的请求都会被映射到/data/images本地磁盘目录,把所有其他的URI请求都传给配置的被代理的serverhttp://localhost:8080/

 6.2. 重要的参数

6.2.1.  proxy_pass: 

  该指令是反向代理的基本指令,用于设置代理服务器的协议和地址;对于一个client的请求,proxy_pass指令通过以下方式进行uri的转发: 

  • 如果proxy_pass指令的参数没有URI,那么请求的URI会被原样的传递给internal server。
  • 如果proxy_pass指令的参数含有URI,client请求的URI匹配该location的部分将会被proxy_pass的path参数替换。
  • 例如:请求为127.0.0.1/name/index.html 会被转发为:127.0.0.1/remote/index.html

6.2.2.  proxy_pass_header: 

  语法:proxy_pass_header field 
  field参数是http所有的header名字,具体可以参考: [HTTP/1.1协议][1] P100 chapter14关于HTTP协议所有header field的定义。

6.2.3.  proxy_set_header: 

  语法:proxy_set_header field value; 
  该指令用于将client传递给proxy server的request header重新定义或者添加字段。Value可以是文本,变量和两者结合。 
  如果set 的header field的值为空,那么这个header是不会传递给proxy server的

6.3. Nginx实现反向代理

两个域名指向同一台nginx服务器,用户访问不同的域名显示不同的网页内容。

两个域名是www.sian.com.cn和www.sohu.com

nginx服务器使用虚拟机192.168.25.148

 技术分享图片

第一步:安装两个tomcat,分别运行在8080和8081端口。

第二步:启动两个tomcat。

第三步:反向代理服务器的配置

复制一个server节点,将root改成proxy_pass,配置了proxy_pass之后服务器不提供服务器,只是请求的转发。

配置upstream

upstream tomcat1 {

                         server 192.168.25.148:8080;

    }

    server {

        listen       80;

        server_name  www.sina.com.cn;

 

        #charset koi8-r;

 

        #access_log  logs/host.access.log  main;

 

        location / {

            proxy_pass   http://tomcat1;

            index  index.html index.htm;

        }

    }

    upstream tomcat2 {

                         server 192.168.25.148:8081;

    }

    server {

        listen       80;

        server_name  www.sohu.com;

 

        #charset koi8-r;

 

        #access_log  logs/host.access.log  main;

 

        location / {

            proxy_pass   http://tomcat2;

            index  index.html index.htm;

        }

    }

第四步:nginx重新加载配置文件

第五步:配置域名

在hosts文件中添加域名和ip的映射关系

192.168.25.148 www.sina.com.cn

192.168.25.148 www.sohu.com

 

7.   负载均衡

如果一个服务由多台服务器提供,需要把负载分配到不同的服务器处理,需要负载均衡。

Nginx提供的负载均衡策略有2种:内置策略扩展策略内置策略为轮询,加权轮询,Ip hash。扩展策略,就天马行空,只有你想不到的没有他做不到的。

 upstream tomcat2 {

       server 192.168.25.148:8081;

       server 192.168.25.148:8082;

  }

 

可以根据服务器的实际情况调整服务器权重weight。权重越高分配的请求越多,权重越低,请求越少。默认是都是1,是轮询机制。

 upstream tomcat2 {

       server 192.168.25.148:8081;

       server 192.168.25.148:8082 weight=2;

    }

 

8.   Nginx的高可用(了解)

要实现nginx的高可用,需要实现备份机。

 

8.1. 什么是负载均衡高可用

       nginx作为负载均衡器,所有请求都到了nginx,可见nginx处于非常重点的位置,如果nginx服务器宕机后端web服务将无法提供服务,影响严重。

       为了屏蔽负载均衡服务器的宕机,需要建立一个备份机。主服务器和备份机上都运行高可用(High Availability)监控程序,通过传送诸如“I am alive”这样的信息来监控对方的运行状况。当备份机不能在一定的时间内收到这样的信息时,它就接管主服务器的服务IP并继续提供负载均衡服务;当备份管理器又从主管理器收到“I am alive”这样的信息时,它就释放服务IP地址,这样的主服务器就开始再次提供负载均衡服务。

 

 

 

8.2. keepalived+nginx实现主备

8.2.1.    什么是keepalived

       keepalived是集群管理中保证集群高可用的一个服务软件,用来防止单点故障。

      Keepalived的作用是检测web服务器的状态,如果有一台web服务器死机,或工作出现故障,Keepalived将检测到,并将有故障的web服务器从系统中剔除,当web服务器工作正常后Keepalived自动将web服务器加入到服务器群中,这些工作全部自动完成,不需要人工干涉,需要人工做的只是修复故障的web服务器。

 

8.2.2.    keepalived工作原理

       keepalived是以VRRP协议为实现基础的,VRRP全称Virtual Router Redundancy Protocol,即虚拟路由冗余协议。

       虚拟路由冗余协议,可以认为是实现路由器高可用的协议,即将N台提供相同功能的路由器组成一个路由器组,这个组里面有一个master和多个backup,master上面有一个对外提供服务的vip(VIP = Virtual IP Address,虚拟IP地址,该路由器所在局域网内其他机器的默认路由为该vip),master会发组播,当backup收不到VRRP包时就认为master宕掉了,这时就需要根据VRRP的优先级来选举一个backup当master。这样的话就可以保证路由器的高可用了。

       keepalived主要有三个模块,分别是core、check和VRRP。core模块为keepalived的核心,负责主进程的启动、维护以及全局配置文件的加载和解析。check负责健康检查,包括常见的各种检查方式。VRRP模块是来实现VRRP协议的。

 

详细参考:Keepalived权威指南中文.pdf

 

8.2.3.    keepalived+nginx实现主备过程

 

初始状态

 

 

 

 

主机宕机

 

 

主机恢复

 

 

8.2.4.    高可用环境

两台nginx,一主一备:192.168.101.3和192.168.101.4

两台tomcat服务器:192.168.101.5、192.168.101.6

 

 

8.2.5.    安装keepalived

 

       分别在主备nginx上安装keepalived,参考“安装手册”进行安装:

 

9.   Sso系统分析

9.1. 什么是sso系统

SSO英文全称Single Sign On,单点登录。SSO是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。它包括可以将这次主要的登录映射到其他应用中用于同一个用户的登录的机制。它是目前比较流行的企业业务整合的解决方案之一。

 

 

 

9.2. 为什么要有单点登录系统

9.2.1.    传统的登录实现方式

 

 

此方式在只有一个web工程时是没有问题。

 

9.2.2.    集群环境下

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

集群环境下会出现要求用户多次登录的情况。

解决方案:

1、配置tomcat集群。配置tomcatSession复制。节点数不要超过5个。

2、可以使用Session服务器,保存Session信息,使每个节点是无状态。需要模拟Session。

 

单点登录系统是使用redis模拟Session,实现Session的统一管理。

 

 

 

10.         Sso系统的实现

 

 

需要创建一个sso服务工程,可以参考taotao-manager创建。

10.1.    工程搭建

Taotao-sso(pom聚合工程)

   |--taotao-sso-interface(jar)

   |--taotao-sso-Service(war)

 

可以参考taotao-manager创建

 

10.1.1.             Taotao-sso

 

Pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

     <modelVersion>4.0.0</modelVersion>

     <parent>

         <groupId>com.taotao</groupId>

         <artifactId>taotao-parent</artifactId>

         <version>0.0.1-SNAPSHOT</version>

     </parent>

     <groupId>com.taotao</groupId>

     <artifactId>taotao-sso</artifactId>

     <version>0.0.1-SNAPSHOT</version>

     <packaging>pom</packaging>

     <dependencies>

         <dependency>

              <groupId>com.taotao</groupId>

              <artifactId>taotao-common</artifactId>

              <version>0.0.1-SNAPSHOT</version>

         </dependency>

     </dependencies>

     <!-- 配置tomcat插件 -->

     <build>

         <plugins>

              <plugin>

                   <groupId>org.apache.tomcat.maven</groupId>

                   <artifactId>tomcat7-maven-plugin</artifactId>

                   <configuration>

                       <port>8087</port>

                       <path>/</path>

                   </configuration>

              </plugin>

         </plugins>

     </build>

</project>

10.1.2.             taotao-sso-interface

 

 

10.1.3.             taotao-sso-service

 

Pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

      <modelVersion>4.0.0</modelVersion>

      <parent>

           <groupId>com.taotao</groupId>

           <artifactId>taotao-sso</artifactId>

           <version>0.0.1-SNAPSHOT</version>

      </parent>

      <artifactId>taotao-sso-service</artifactId>

      <packaging>war</packaging>

      <dependencies>

           <dependency>

                 <groupId>com.taotao</groupId>

                 <artifactId>taotao-manager-dao</artifactId>

                 <version>0.0.1-SNAPSHOT</version>

           </dependency>

           <dependency>

                 <groupId>com.taotao</groupId>

                 <artifactId>taotao-sso-interface</artifactId>

                 <version>0.0.1-SNAPSHOT</version>

           </dependency>

           <!-- spring的依赖 -->

           <!-- Spring -->

           <dependency>

                 <groupId>org.springframework</groupId>

                 <artifactId>spring-context</artifactId>

            </dependency>

           <dependency>

                 <groupId>org.springframework</groupId>

                 <artifactId>spring-beans</artifactId>

           </dependency>

           <dependency>

                 <groupId>org.springframework</groupId>

                 <artifactId>spring-webmvc</artifactId>

           </dependency>

           <dependency>

                 <groupId>org.springframework</groupId>

                 <artifactId>spring-jdbc</artifactId>

           </dependency>

           <dependency>

                 <groupId>org.springframework</groupId>

                 <artifactId>spring-aspects</artifactId>

           </dependency>

           <dependency>

                 <groupId>org.springframework</groupId>

                 <artifactId>spring-jms</artifactId>

           </dependency>

           <dependency>

                 <groupId>org.springframework</groupId>

                 <artifactId>spring-context-support</artifactId>

           </dependency>

           <!-- dubbo相关 -->

           <dependency>

                 <groupId>com.alibaba</groupId>

                 <artifactId>dubbo</artifactId>

                 <!-- 排除依赖 -->

                 <exclusions>

                      <exclusion>

                            <groupId>org.springframework</groupId>

                            <artifactId>spring</artifactId>

                      </exclusion>

                      <exclusion>

                            <groupId>org.jboss.netty</groupId>

                            <artifactId>netty</artifactId>

                      </exclusion>

                 </exclusions>

           </dependency>

           <dependency>

                 <groupId>org.apache.zookeeper</groupId>

                 <artifactId>zookeeper</artifactId>

           </dependency>

           <dependency>

                 <groupId>com.github.sgroschupf</groupId>

                 <artifactId>zkclient</artifactId>

           </dependency>

           <!-- Redis客户端 -->

           <dependency>

                 <groupId>redis.clients</groupId>

                 <artifactId>jedis</artifactId>

           </dependency>

      </dependencies>

</project>

 

10.1.4.             框架整合

 

 

10.2.    表现层工程

表现层工程包含登录和注册页面,需要调用sso服务实现。

给app提供服务,restful形式的服务。

Taotao-sso-web(war包)

可以参考taotao-manager-web创建。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

     <modelVersion>4.0.0</modelVersion>

     <parent>

         <groupId>com.taotao</groupId>

         <artifactId>taotao-parent</artifactId>

         <version>0.0.1-SNAPSHOT</version>

     </parent>

     <groupId>com.taotao</groupId>

     <artifactId>taotao-sso-web</artifactId>

     <version>0.0.1-SNAPSHOT</version>

     <packaging>war</packaging>

     <dependencies>

         <dependency>

              <groupId>com.taotao</groupId>

              <artifactId>taotao-sso-interface</artifactId>

              <version>0.0.1-SNAPSHOT</version>

         </dependency>

         <!-- Spring -->

         <dependency>

              <groupId>org.springframework</groupId>

              <artifactId>spring-context</artifactId>

         </dependency>

         <dependency>

              <groupId>org.springframework</groupId>

              <artifactId>spring-beans</artifactId>

         </dependency>

         <dependency>

              <groupId>org.springframework</groupId>

              <artifactId>spring-webmvc</artifactId>

         </dependency>

         <dependency>

              <groupId>org.springframework</groupId>

              <artifactId>spring-jdbc</artifactId>

         </dependency>

         <dependency>

              <groupId>org.springframework</groupId>

              <artifactId>spring-aspects</artifactId>

         </dependency>

         <dependency>

              <groupId>org.springframework</groupId>

              <artifactId>spring-jms</artifactId>

         </dependency>

         <dependency>

              <groupId>org.springframework</groupId>

              <artifactId>spring-context-support</artifactId>

         </dependency>

         <!-- JSP相关 -->

         <dependency>

              <groupId>jstl</groupId>

              <artifactId>jstl</artifactId>

         </dependency>

         <dependency>

              <groupId>javax.servlet</groupId>

              <artifactId>servlet-api</artifactId>

              <scope>provided</scope>

         </dependency>

         <dependency>

              <groupId>javax.servlet</groupId>

              <artifactId>jsp-api</artifactId>

              <scope>provided</scope>

         </dependency>

         <!-- dubbo相关 -->

         <dependency>

              <groupId>com.alibaba</groupId>

              <artifactId>dubbo</artifactId>

              <!-- 排除依赖 -->

              <exclusions>

                   <exclusion>

                       <groupId>org.springframework</groupId>

                       <artifactId>spring</artifactId>

                   </exclusion>

                   <exclusion>

                       <groupId>org.jboss.netty</groupId>

                       <artifactId>netty</artifactId>

                   </exclusion>

              </exclusions>

         </dependency>

         <dependency>

              <groupId>org.apache.zookeeper</groupId>

              <artifactId>zookeeper</artifactId>

         </dependency>

         <dependency>

              <groupId>com.github.sgroschupf</groupId>

              <artifactId>zkclient</artifactId>

         </dependency>

         <dependency>

              <groupId>junit</groupId>

              <artifactId>junit</artifactId>

         </dependency>

     </dependencies>

     <!-- 配置tomcat插件 -->

     <build>

         <plugins>

              <plugin>

                   <groupId>org.apache.tomcat.maven</groupId>

                   <artifactId>tomcat7-maven-plugin</artifactId>

                   <configuration>

                       <port>8088</port>

                       <path>/</path>

                   </configuration>

              </plugin>

         </plugins>

     </build>

</project>

 

 

 

 

 

 

Nginx     http服务器

       可做虚拟主机,在一个服务器上跑多个网站;但是默认端口只有80,80端口需要公用

Nginx可以解决这个问题

 

 

Nginx安装:

       由于市面上linux发行版本过多,版本之间的压缩包格式不同,所以nginx提供nginx的源码安装.

 

https 加密的http协议 比http安全但效率稍微要低一些

 

负载均衡:软负载,硬负载

F5硬负载第四层负载 :传输层负载

nginx是第七层应用层负载

 

LVS实现第四层的软负载,能实现F5的60的负载功能

 

集群 多台服务器做一个服务

Nginx学习笔记

原文:https://www.cnblogs.com/arjenlee/p/9243218.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!