nginx简介及配置

nginx的简介

Nginx是俄罗斯人编写的十分轻量级的HTTP服务器,Nginx,它的发音为“engine X”,是一个高性能的HTTP和反向代理服务器,同时也是一个IMAP/POP3/SMTP 代理服务器。Nginx是由俄罗斯人 Igor Sysoev为俄罗斯访问量第二的 Rambler.ru站点开发的,它已经在该站点运行超过两年半了。Igor Sysoev在建立的项目时,使用基于BSD许可。

Nginx工作原理

Nginx由内核和模块组成,完成工作是通过查找配置文件将客户端请求映射到一个location block(location是用于URL匹配的命令),location配置的命令会启动不同模块完成工作。

Nginx模块分为核心模块,基础模块和第三方模块。

核心模块:HTTP模块、EVENT模块(事件)、MAIL模块。

基础模块:HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块、HTTP Rewrite模块。

第三方模块:HTTP Upstream Request Hash模块、Notice模块、HTTP Access Key模块。

如果你想编译和安装Tengine,下面是一个简单的例子:

$ ./configure 检查
$ make  编译
$ sudo make install 安装

tengine安装及配置

一。安装过程
1.下载
http://tengine.taobao.org/download.html 找到下载包并且下载(Tengine-2.2.0.tar.gz)
2.解压
tar zxvf Tengine-2.2.0.tar.gz
3.配置检查
解压目录 cd tengine-2.2.0
进入解压后的目录 ./configure

异常1:  
   [root@bogon tengine]# ./configure  
checking for OS  
 + Linux 3.10.0-327.el7.x86_64 x86_64  
checking for C compiler ... not found  

./configure: error: C compiler cc is not found  
也就是c编译器 gcc找不到  
 安装gcc  yum -y install gcc  

继续检查  
./configure
异常2
checking for PCRE library ... not found
checking for PCRE library in /usr/local/ ... not found
checking for PCRE library in /usr/include/pcre/ ... not found
checking for PCRE library in /usr/pkg/ ... not found
checking for PCRE library in /opt/local/ ... not found
缺少pcre和pcre-devel 安装 yum -y install pcre pcre-devel  
 这里安装好后 可以通过  
  Rpm -qa | grep pcre找到所有pcre的包  
  Rpm -ql 完整包名  查看安装的路径 

继续检查  ./configure
异常3:  
 error: SSL modules require the OpenSSL library.
You can either do not enable the modules, or install the OpenSSL library
into the system, or build the OpenSSL library statically from the source
with nginx by using --with-openssl=<path> option.
缺少openssl和openssl-devel 安装 yum -y install openssl openssl-devel  

继续检测成功 可以同构日志看到 需要pcre openssl zlib(安装openssl自动安装)的库  
checking for PCRE library ... found  
checking for PCRE JIT support ... found  
checking for OpenSSL library ... found  
checking for zlib library ... found  
creating objs/Makefile  

./nginx -t检查配置
./nginx -s reload 重新启动

4.安装
make install 安装完成 安装目录为/usr/local/nginx
找到 /usr/local/nginx/sbin/nginx -V 查看所有加载的模块

[root@bogon sbin]# ./nginx -V  
Tengine version: Tengine/2.2.0 (nginx/1.8.1)  
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-11) (GCC)  
TLS SNI support enabled  
configure arguments:  
nginx: loaded modules:  
nginx:     ngx_core_module (static)  
nginx:     ngx_errlog_module (static)  
nginx:     ngx_conf_module (static)  
nginx:     ngx_dso_module (static)  
nginx:     ngx_events_module (static)  

然后进入cd sbin启动nginx 用./nginx可直接执行
/usr/local/nginx/sbin/nginx start|stop|restart 启动和关闭ngix服务
nginx命令参数

  nginx -m 显示所有加载的模块
  nginx -l 显示所有可以使用的指令
  nginx -t 检查nginx的配置文件是否正确
  nginx -s 启动nginx
  nginx -s reload 重启nginx
  nginx -s stop 停止nginx
  yum -y install ntpdate 用于远程更新时间
  阿里云提供的时间服务器ntpdate timel.aliyum.com 或者115.28.122.198
  chkconfig iptables off关闭防火墙不用每次都关闭

Nginx配置文件(/usr/local/nginx/conf/nginx.conf)
配置文件主要由四部分组成:main(全区设置),server(主机配置),upstream(负载均衡服务器设置),和location(URL匹配特定位置设置)。

Nginx配置upstream实现负载均衡
如果Nginx没有仅仅只能代理一台服务器的话,那它也不可能像今天这么火,Nginx可以配置代理多台服务器,当一台服务器宕机之后,仍能保持系统可用。具体配置过程如下:/usr/local/nginx/conf”配置文件目录

  1. 在http节点下,添加upstream节点。
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;

    upstream backend {
            server 192.168.73.130:8080       max_fails=3 fail_timeout=30s;
            server 192.168.73.1:8080       max_fails=3 fail_timeout=30s;

    }
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;



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

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
  1. 将server节点下的location节点中的proxy_pass配置为:http:// + upstream名称,即“
    http://favtomcat”.
   location / {
            root   html;
            index  index.html index.htm;
            proxy_pass http://backend;
        }
  1. 现在负载均衡初步完成了。upstream按照轮询(默认)方式进行负载,每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。虽然这种方式简便、成本低廉。但缺点是:可靠性低和负载分配不均衡。适用于图片服务器集群和纯静态页面服务器集群。
    除此之外,upstream还有其它的分配策略,分别如下:
    weight(权重)
    指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。如下所示,10.0.0.88的访问比率要比10.0.0.77的访问比率高一倍。
    ip_hash(访问ip)
    每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
    fair(第三方)
    按后端服务器的响应时间来分配请求,响应时间短的优先分配。与weight分配策略类似。
    url_hash(第三方)
    按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。
    注意:在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method是使用的hash算法。
    upstream还可以为每个设备设置状态值,这些状态值的含义分别如下:
    down 表示单前的server暂时不参与负载.
    weight 默认为1.weight越大,负载的权重就越大。
    max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误.
    fail_timeout : max_fails次失败后,暂停的时间。
    ackup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

反向代理

在计算机世界里,由于单个服务器的处理客户端(用户)请求能力有一个极限,当用户的接入请求蜂拥而入时,会造成服务器忙不过来的局面,可以使用多个服务器来共同分担成千上万的用户请求,这些服务器提供相同的服务,对于用户来说,根本感觉不到任何差别。

反向代理的实现
1)需要有一个负载均衡设备来分发用户请求,将用户请求分发到空闲的服务器上

2)服务器返回自己的服务到负载均衡设备

3)负载均衡将服务器的服务返回用户

二。配置文件
默认配置文件位于

/usr/local/nginx/conf/nginx.conf

常用的配置选项

#user  nobody;
#工作的cpu的内核数  默认应该是和当前电脑的cpu一致  设置为auto自动获取当前机器  
worker_processes  1;
#ngx_http_log_module模块功能    
#语法为 error_log 存储的log文件路径 [debug | info | notice | warn | error | crit]  
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#定义存储nginx主进程ID的file。 nigix可能建立虚拟主机是 会创建多个进程  
#pid        logs/nginx.pid;


events {
    #设置每个工作进程可以打开的最大并发连接数。
    worker_connections  1024;
}

# load modules compiled as Dynamic Shared Object (DSO)
#
#dso {
#    load ngx_http_fastcgi_module.so;
#    load ngx_http_rewrite_module.so;
#}
#配置http服务器  
http {
     #包含其他语法正确的配置文件   
    include       mime.types;
    #设置默认的mini类型  
    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压缩 压缩需要时间 但是压缩后 可以节省带宽  
    #gzip  on;

    upstream backend {
            server 192.168.73.130:8080       ;
            server 192.168.73.1:8080       ;
            #解决session丢失问题  粘性session 存在的问题就是永远走一台机器 达不到负载均衡的效果
            session_sticky;
            #健康检查
            #interval表示检查的时间间隔 rise=2 表示3秒中之内有连续2次返回2xx或3xx表示是健康的
            #fall=5表示连续失败五次才表示失败 timeout=1000超时时间   
            check interval=3000 rise=2 fall=5 timeout=1000 type=http;
            check_http_send "HEAD / HTTP/1.0\r\n\r\n";
            #http_2xx http_3xx表示是存活的
            check_http_expect_alive http_2xx http_3xx;
    }
    #配置虚拟主机 
    server {
        #虚拟主机监听端口  
        listen       80;
        #虚拟主机监听的ip(同一电脑可能多个ip)或者域名  
        #添加虚拟ip ifconfig 网卡名(可以通过ifconfig查看):1 192.168.58.134 netmask 255.255.255.0 up  
        #删除虚拟ip ifconfig 网卡名(可以通过ifconfig查看):1 down  
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;


        #除了/status 以外的其他的所有路径
        location / {
            root   html;
            index  index.html index.htm;
            proxy_pass http://backend;
            #流程控制            #http://tengine.taobao.org/nginx_docs/cn/docs/http/ngx_http_rewrite_module.html
            #当用户访问/admin/路径都阻止访问
            if ( $uri ~* /admin/.*$){
            #返回错误页面
                return 505;
            }
        }

        #只检测 /status的路径 健康检查配置http://tengine.taobao.org/文档/健康检查模块功能
        location /status {
            check_status;
            #访问/status需要验证用户名和密码来限制对资源的访问
            auth_basic           "closed site";
            #不能用相对路径conf/htpasswd
            auth_basic_user_file /usr/local/nginx/conf/htpasswd; #加密
            access_log   off;
            allow 192.168.73.1; #只允许在windows中访问
            #allow 192.168.73.130; #只允许在linux中访问
            deny all; #阻止所有的访问
        }
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        # html目录在nginx/html
        error_page   500 502 503 504  /50x.html;
        error_page   505   /my505.html;
        #当根路径访问时 必须 http://localhost/ 自动进入根目录 html下找 index.html文件  
        location = /50x.html {
            root   html;
        }
        location = /my505.html {
            root   html;
        }
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        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;
    #    }
    #}
}

location其他配置
ngx_http_access_module
模块 限制客户端访问ip(http://tengine.taobao.org/nginx_docs/cn/docs/http/ngx_http_access_module.html
配置范例
location / {
deny 192.168.58.1;
allow all;
}
这里 192.168.58.1被禁止访问 除了58.1其他都可以访问
58.1访问 出现 403被禁止 其他ip都可以正常访问(linux访问可以使用 wget 地址 或者 curl地址) 可以通过logs/access.log查看访问服务的客户端信息
这里写图片描述
模块ngx_http_auth_basic_module 允许使用“HTTP基本认证”协议验证用户名和密码来限制对资源的访问。
也可以通过 地址来限制访问。 使用satisfy 指令就能同时通过地址和密码来限制访问。

配置范例

location / {  
    auth_basic            "密码验证";  
    auth_basic_user_file   /usr/local/nginx/conf/htpasswd; #加密  
 }  

效果图
这里写图片描述
ngx_http_upstream_session_sticky_module
该模块是一个负载均衡模块,通过cookie实现客户端与后端服务器的会话保持, 在一定条件下可以保证同一个客户端访问的都是同一个后端服务器。

负载均衡时session会丢失
解决session丢失的问题
http://tengine.taobao.org/文档/session_sticky模块功能

 upstream backend {
            server 192.168.73.130:8080       ;
            server 192.168.73.1:8080       ;
            #在集群中加入下面这个指令  粘性session 存在的问题就是永远走一台机器 达不到负载均衡的效果 
            #解决session丢失问题  粘性session 存在的问题就是永远走一台机器 达不到负载均衡的效果
            session_sticky;

    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值