美文网首页大数据与云计算
大数据基础——Nginx服务器基本配置

大数据基础——Nginx服务器基本配置

作者: So_ProbuING | 来源:发表于2018-01-30 17:08 被阅读0次

    Nginx

    Nginx(“engine x”) 是一个高性能的HTTP和反向代理服务器,也是一个i额IMAP/POP3/SMTP代理服务器
    Nginx的第一个公开版本0.1.0发布于2004年10月4日,因为Nginx的稳定性、丰富的功能集低系统资源的消耗而闻名。
    在官方测试中nginx能够支撑大的并发链接,并且对CPU、内存的等资源消耗却非常低,运行很稳定

    Nginx的主要功能

    • web服务器
    • web reverse proxy
    • smtp reverse proxy

    典型代表应用

    阿里云 阿里巴巴 网易 爱奇艺 新浪。。。

    典型优缺点

    1.nginx处理请求是异步非阻塞的,而apache是阻塞的,在高并发下nginx能够保持低资源消耗高性能
    2.nginx高度模块化的设计,编写模块相对简单
    3.nginx社区活跃,产品迭代迅速
    4.Nginx配置间接,部署迅速
    5.对于apache是同步多进程模型,一个连接对应一个进程;nginx是异步的,多个连接对应一个进程

    Tengine

    Tengine是nginx的加强版,也是封装版,淘宝开源
    Tengine要比nginx更加强大,支持动态模块加载,加入模块不需要重新编译整个Tengine
    更加强大的负载均衡能力,包括一致性hash模块、会话保持模块,还可以对后端的服务器进行主动健康检查。

    安装Tengine

    安装前准备

    1.安装依赖gcc openssl-devel pcre-devel zlib-devel
    安装命令: yum install gcc openssl-devel pcre-devel zlib-devel
    2.创建用户和用户组,目的是方便nginx运行而不影响linux安全

    groupadd -r nginx
    useradd -r -g nginx -M nginx 
     -M表示不创建用户的家目录
    
    • 简洁方式
    ./configure \
    --prefix=/usr/tengine
    make && make install 
    
    • 详细安装配置
    /configure \
     --prefix=/usr \                        # 安装位置
     --sbin-path=/usr/sbin/nginx \ # 启动文件位置
     --conf-path=/etc/nginx/nginx.conf \ # 配置文件位置
     --error-log-path=/var/log/nginx/error.log \ # 错误日志路径
     --http-log-path=/var/log/nginx/access.log \ #http请求日志路径
     --pid-path=/var/run/nginx/nginx.pid \ # 进程号 
     --lock-path=/var/lock/nginx.lock \ # 锁文件路径
     --user=nginx \                            # 指定用户
     --group=nginx \                         # 制定组
     --with-http_ssl_module \          # 加载的模块
     --with-http_flv_module \        
     --with-http_stub_status_module \
     --with-http_gzip_static_module \
     --http-client-body-temp-path=/var/tmp/nginx/client/ \  # 临时文件目录
     --http-proxy-temp-path=/var/tmp/nginx/proxy/ \
     --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
     --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
     --http-scgi-temp-path=/var/tmp/nginx/scgi \
     --with-pcre
    - make && make install 开始安装
    
    • 默认安装目录配置
      ···
      ./configure
      --prefix=/opt/sxt/soft/tengine-2.1.0/
      --error-log-path=/var/log/nginx/error.log
      --http-log-path=/var/log/nginx/access.log
      --pid-path=/var/run/nginx/nginx.pid
      --lock-path=/var/lock/nginx.lock
      --with-http_ssl_module
      --with-http_flv_module
      --with-http_stub_status_module
      --with-http_gzip_static_module
      --http-client-body-temp-path=/var/tmp/nginx/client/
      --http-proxy-temp-path=/var/tmp/nginx/proxy/
      --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/
      --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi
      --http-scgi-temp-path=/var/tmp/nginx/scgi
      --with-pcre
      – make && make install
      – 启动和配置路径用默认的,用户和用户组限制,都去掉
      – 其中/var/tmp/nginx/client/目录需要手动创建
      ···

    添加启动服务

    在/etc/init.d 目录下创建脚本 nginx

    #!/bin/bash
    #
    # chkconfig: - 85 15
    # description: nginx is a World Wide Web server. It is used to serve
    # Source function library.
    . /etc/rc.d/init.d/functions
     
    # Source networking configuration.
    . /etc/sysconfig/network
     
    # Check that networking is up.
    [ "$NETWORKING" = "no" ] && exit 0
     
    nginx="/usr/tengine-2.1/sbin/nginx"  # 安装位置
    prog=$(basename $nginx)
     
    NGINX_CONF_FILE="/usr/tengine-2.1/conf/nginx.conf"
     
    #[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
     
    lockfile=/var/lock/subsys/nginx
     
    #make_dirs() {
    #   # make required directories
    #   user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
    #   options=`$nginx -V 2>&1 | grep 'configure arguments:'`
    #   for opt in $options; do
    #       if [ `echo $opt | grep '.*-temp-path'` ]; then
    #           value=`echo $opt | cut -d "=" -f 2`
    #           if [ ! -d "$value" ]; then
    #               # echo "creating" $value
    #               mkdir -p $value && chown -R $user $value
    #           fi
    #       fi
    #   done
    #}
     
    start() {
        [ -x $nginx ] || exit 5
        [ -f $NGINX_CONF_FILE ] || exit 6
    #    make_dirs
        echo -n $"Starting $prog: "
        daemon $nginx -c $NGINX_CONF_FILE
        retval=$?
        echo
        [ $retval -eq 0 ] && touch $lockfile
        return $retval
    }
     
    stop() {
        echo -n $"Stopping $prog: "
        killproc $prog -QUIT
        retval=$?
        echo
        [ $retval -eq 0 ] && rm -f $lockfile
        return $retval
    }
     
    restart() {
        configtest || return $?
        stop
        sleep 1
        start
    }
     
    reload() {
        configtest || return $?
        echo -n $"Reloading $prog: "
    #  -HUP是nginx平滑重启参数  
        killproc $nginx -HUP
        RETVAL=$?
        echo
    }
     
    force_reload() {
        restart
    }
     
    configtest() {
      $nginx -t -c $NGINX_CONF_FILE
    }
     
    rh_status() {
        status $prog
    }
     
    rh_status_q() {
        rh_status >/dev/null 2>&1
    }
     
    case "$1" in
        start)
            rh_status_q && exit 0
            $1
            ;;
        stop)
            rh_status_q || exit 0
            $1
            ;;
        restart|configtest)
            $1
            ;;
        reload)
            rh_status_q || exit 7
            $1
            ;;
        force-reload)
            force_reload
            ;;
        status)
            rh_status
            ;;
        condrestart|try-restart)
            rh_status_q || exit 0
                ;;
        *)
            echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
            exit 2
    esac
    

    修改nginx启动文件的执行权限

    chmod +x nginx
    

    添加文件到系统服务中

    chkconfig --add nginx
    # 验证添加是否成功
    chkconfig --list nginx
    

    添加到开机启动

    chkconfig nginx on
    

    启动、停止、重新加载

    service nginx start|stop|reload
    

    配置

    nginx配置文件在安装目录下的/conf/nginx.conf

    # 定义Nginx运行的用户和用户组
    #user  nobody;
    # nginx进程数,一般建议设置为等于CPU总核心数
    worker_processes  1;
    
    # 全局错误日志定义类型 【debug|info|notice|warn|error|crit】
    #error_log  logs/error.log;
    #error_log  logs/error.log  notice;
    #error_log  logs/error.log  info;
    #error_log  "pipe:rollback logs/error_log interval=1d baknum=7 maxsize=2G";
    
    # 进程文件
    #pid        logs/nginx.pid;
    
    
    events {
    # 单个进程最大连接数 nginx并发总数是worker_processes和worker_connections的乘积
        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;
        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;
        #access_log  "pipe:rollback logs/access_log interval=1d baknum=7 maxsize=2G"  main;
      # 开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为on,如果用来进行下载等应用磁盘IO负载的应用,可设置为off,以平衡磁盘与网络IO处理速度,降低系统的负载
        sendfile        on;
        #tcp_nopush     on;
        autoindex 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;
            #access_log  "pipe:rollback logs/host.access_log interval=1d baknum=7 maxsize=2G"  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;
            #}
        }
    
    
        # 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;
        #    }
        #}
    
    }
    
    

    虚拟主机

    虚拟主机是一种特殊的软硬件技术,可以将网络上的每一台计算机分成多个虚拟主机,每个虚拟主机可以独立对外提供www服务,这样就可以实现一台主机对外提供多个web服务,每个虚拟主机之间独立。互相不影响


    xunizhuji.png

    虚拟主机的分类

    通过nginx可以实现虚拟主机的配置,nginx支持三种类型的
    虚拟主机配置,
    – 1、基于ip的虚拟主机, (一块主机绑定多个ip地址)
    – 2、基于域名的虚拟主机(servername)
    – 3、基于端口的虚拟主机(listen如果不写ip端口模式)
    – 示例基于虚拟机ip的配置,这里需要配置多个ip

    基于ip的虚拟主机

    基于ip的虚拟主机,可以配置多个ip地址,但是多个ip地址属于同一个主机

    # 编辑 nginx的配置文件。
      server {
     45         listen       80;
     46         server_name  192.168.1.63; # ip地址1
     47 
     48         #charset koi8-r;
     49 
     50         #access_log  logs/host.access.log  main;
     51         #access_log  "pipe:rollback logs/host.access_log interval=1d baknum=7 maxsize=2G"  main;
     52 
     53         location / { #地址1对应的根目录1
     54             root   html;
     55             index  index.html index.htm;
     56         }
     57         #error_page  404              /404.html;
     58 
     59         # redirect server error pages to the static page /50x.html
     60         #
     61         error_page   500 502 503 504  /50x.html;
     62         location = /50x.html {
     63             root   html;
     64         }
     65 
     66     server {
     67         listen     80;
     68         server_name 192.168.1.69;#ip地址2
     69         location / { #ip地址2对应的根目录
     70         root /opt/html
     71         index index.html index.htm
     72         }
     73         }
    
    

    虚拟机配置虚拟ip

    ifconfig eth0:192.168.1.69 netmask 255.255.255.0
    # 删除虚拟ip
    ifconfig eth0:1 down  
    

    重启nginx

    • 对于虚拟ip的nginx 平滑启动不会生效,所以需要使用重启命令
    # systemctl restart nginx
    

    访问不同的ip会进入到不同的根目录中

    基于域名的虚拟主机

    编辑配置文件

      server {
     45         listen       80;
     46         server_name  www.nginx1.com; # 域名地址1
     47         location / {  # 域名地址1目录
     48             root   html;
     49             index  index.html index.htm;
     50         }   
     51         error_page   500 502 503 504  /50x.html;
     52         location = /50x.html {
     53             root   html;
     54         }   
     55     }   
     56     server {
     57         listen     80;
     58         server_name www.nginx2.com; #域名地址2
     60          location / { #域名地址2目录
     61              root /opt/html;
     62              index  index.html index.htm;
     63          }   
     64          
     65          
     66     }  
    

    由于是练习环境,编辑win hosts文件

    ···
    192.168.1.63 www.nginx1.com
    192.168.1.63 www.nginx2.com
    ···

    重新加载nginx.conf

    systemctl reload nginx
    

    基于端口的虚拟主机

    编辑配置文件

     server {
     45         listen       80; # 监听端口1
     46         server_name  localhost;
     47         location / {
     48             root   html;
     49             index  index.html index.htm;
     50         }
     51         error_page   500 502 503 504  /50x.html;
     52         location = /50x.html {
     53             root   html;
     54         }
     55     }
     56     server {
     57         listen     8090; # 监听端口2
     58         server_name localhost;
     59 
     60          location / {
     61              root /opt/html;
     62              index  index.html index.htm;
     63          }
     64 
     65 
     66     }
    

    重新加载nginx

    systemctl reload nginx
    

    nginx 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, 请求“/documents/document.html”匹配配置C, 请求“/images/1.gif”匹配配置D, 请求“/documents/1.jpg”匹配配置E。

    nginx location配置

    • location [=||*|^~]uri{...}
      • location URI{}:对当前路径及子路径下的所有对象都生效
      • location =URI{} 精确匹配指定的路径,不包括子路径,只对当前资源生效
      • location ~* URI{} 模式匹配URI ,此处的URI可使用正则表达式 区分字符大小写,*不区分
      • 如果匹配使用^~作为前缀,搜索匹配到后就停止

    优先级

    = > ^~ > ~|~* > /|/dir/
    

    nginx 模块

    ngx_http_access_module 允许限制某些ip地址的客户端访问

    location / {
        deny  192.168.1.1;
        allow 192.168.1.0/24;
        allow 10.1.1.0/16;
        allow 2001:0db8::/32;
        deny  all;
    }
    规则按照顺序依次检测,直到匹配到第一条规则。 在这个例子里,IPv4的网络中只有 10.1.1.0/16 和 192.168.1.0/24允许访问,但 192.168.1.1除外, 对于IPv6的网络,只有2001:0db8::/32允许访问。 在规则很多的情况下,使用 ngx_http_geo_module 模块变量更合适。
    
    

    指令
    语法: allow address | CIDR | all;
    默认值: —
    上下文: http, server, location, limit_except
    允许指定的网络地址访问。

    语法: deny address | CIDR | all;
    默认值: —
    上下文: http, server, location, limit_except
    拒绝指定的网络地址访问。

    ngx_http_auth_basic_module 用户认证访问

    配置范例

    location / {
        auth_basic           "closed site";
        auth_basic_user_file conf/htpasswd;
    }
    
    

    语法

    语法: auth_basic string | off;
    默认值:
    auth_basic off;
    上下文: http, server, location, limit_except
    开启使用“HTTP基本认证”协议的用户名密码验证。 指定的参数被用作 域。 参数off可以取消继承自上一个配置等级 auth_basic 指令的影响。

    语法: auth_basic_user_file file;
    默认值: —
    上下文: http, server, location, limit_except
    指定保存用户名和密码的文件,格式如下:

    comment

    name1:password1
    name2:password2:comment
    name3:password3
    写明文无效
    密码应该使用crypt()函数加密。 可以用Apache发行包中的htpasswd命令来创建此类文件。

    相关文章

      网友评论

        本文标题:大数据基础——Nginx服务器基本配置

        本文链接:https://www.haomeiwen.com/subject/zzxfzxtx.html