• 7.Web基础之Nginx


    1. Nginx基本概述

    nginx是一个开源且高性能、可靠的http web服务、代理服务。
    开源:直接获取源代码
    高性能:支持海量并发
    可靠:服务稳定

    1.1 我们为什么选择Nginx服务

    1.1.1 nginx非常轻量

    功能模块少(源代码仅保留http与核心模块代码,其余不够核心代码会作为插件来安装)
    代码模块化(易读,便于二次开发,对于开发人员非常友好)

    1.1.2 互联网公司都选择nginx

    1.nginx技术成熟,具备的功能是企业最常使用而且最需要的
    2.适合当前主流架构趋势,微服务,云架构,中间层
    3.统一技术栈,降低维护成本,降低技术更新成本。

    1.1.3 nginx采用Epool网络模型,Apache采用select模型

    select:当用户发起一次请求,select模型就会进行一次遍历扫描,从而导致性能低下;
    Epool:当用户发起请求,epool模型会直接进行处理,效率高效,并无连接限制。

    Nginx典型应用场景-c

    2. Nginx快速安装

    nginx软件安装方式有很多种

    1.源码编译>Nginx(1.版本随意 2.安装复杂 3.升级繁琐)
    2.epel仓库
    >Nginx(1.版本较低 2.安装简单 3.配置不易读)
    3.官方仓库==>Nginx(1.版本较新 2.安装简单 3.配置易读,推荐)

    2.1 安装Nginx软件所需依赖包

    [root@web01 ~]# yum install -y gcc gcc-c++ pcre pcre-devel openssl openssl-devel
    

    2.2 配置Nginx官方yum源

    [root@web01 ~]# vim /etc/yum.repos.d/nginx.repo 
    
    [nginx-stable]
    name=nginx stable repo
    baseurl=http://nginx.org/packages/centos/7/$basearch/
    gpgcheck=0
    enabled=1
    gpgkey=https://nginx.org/keys/nginx_signing.key
    

    2.3 安装Nginx服务,启动并假如开机自启

    [root@web01 ~]# yum install -y nginx
    [root@web01 ~]# systemctl start nginx
    [root@web01 ~]# systemctl enable nginx
    

    2.4 通过浏览器访问该服务器ip活url地址

    -c

    2.5 检查Nginx软件版本以及编译参数

    [root@web01 ~]# nginx -v
    nginx version: nginx/1.16.0
    [root@web01 ~]# nginx -V
    nginx version: nginx/1.16.0
    built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) 
    built with OpenSSL 1.0.2k-fips  26 Jan 2017
    TLS SNI support enabled
    configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
    [root@web01 ~]# 
    

    2.6 Nginx配置

    为了让大家更清晰的了解Nginx软件的全貌,可使用rpm -ql nginx 查看真题的目录结构及对应的功能,如下表格整理了Nginx比较重要的配置文件

    2.6.1 Nginx主配置文件

    路径 类型 作用
    /etc/nginx/nginx.conf 配置文件 nginx主配置文件
    /etc/nginx/conf.d/default.conf 配置文件 默认网站配置文件

    2.6.2 Nginx代理相关参数文件

    路径 类型 作用
    /etc/nginx/fastcgi_params 配置文件 fastcgi代理配置文件
    /etc/nginx/scgi_params 配置文件 scgi代理配置文件

    2.6.3 Nginx编码相关参数文件

    路径 类型 作用
    /etc/nginx/win-utf 配置文件 Nginx编码转换映射文件
    /etc/nginx/koi-utf 配置文件 Nginx编码转换映射文件
    /etc/nginx/koi-win 配置文件 Nginx编码转换映射文件
    /etc/nginx/mime.types 配置文件 Content-Type与扩展名

    2.6.4 Nginx管理相关命令

    路径 类型 作用
    /usr/sbin/nginx 命令 Nginx命令行管理终端工具
    /usr/sbin/nginx-debug 命令 Nginx命令行与终端调试工具

    2.6.5 Nginx日志相关目录与文件

    路径 类型 作用
    /var/log/nginx 目录 Nginx默认存放日志目录
    /etc/logrotate.d/nginx 配置文件 Nginx默认的日志切割

    3. Nginx默认配置

    Nginx主配置文件/etc/nginx/nginx.conf是一个纯文本类型的文件,整个配置文件是以区块的形式组织的。一般每个区块以一对大括号{}来表示开始与结束。
    Nginx主配置文件整体分为三块进行学习,分别是CoreModule(核心模块)、EventModule(事件驱动模块)、HttpCoreModule(http内核模块)

    CoreModule(核心模块)

    user  nginx;                                #Nginx进程所使用的用户
    worker_processes  1;                        #Nginx运行的work进程数量(建议与CPU数量一致或auto)
    error_log  /var/log/nginx/error.log warn;   #Nginx错误日志存放路径(警告及警告以上的都会记录)
    pid        /var/run/nginx.pid;              #Nginx服务运行后产生的pid进程号
    

    EventModule(事件驱动模块)

    events {
    worker_connections  1024;                   #每个worker进程支持的最大连接数
    use epool                                   #事件驱动模型,epoll默认
    }
    

    HttpCoreModule(http内核模块)

    http {
        include       /etc/nginx/mime.types;            #包含资源类型文件
        default_type  application/octet-stream;         #默认以下载方式传输给浏览器(前提是该资源在mime.types中无法找到)
        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  /var/log/nginx/access.log  main;    #访问日志
        sendfile        on;
        #tcp_nopush     on;
        keepalive_timeout  65;                          #长连接超时时间
        #gzip  on;                                      #是否开启压缩功能
        include /etc/nginx/conf.d/*.conf;               #包含的配置文件
    
    server {
        listen       80;                                #监听端口
        server_name  localhost;                         #域名
        #charset koi8-r;                                #字符集
        #access_log  /var/log/nginx/host.access.log  main;   #访问日志
        location / {                                    #存放网站路径
            root   /usr/share/nginx/html;               #默认访问首页文件
            index  index.html index.htm;
        }
    }
    

    **http server location扩展了解项

    ① http{}层下允许有许多个server{}层,一个server{}层下又允许有多个location
    ② http{}标签主要用来解决用户的请求与响应
    ③ server{}标签主要用来响应具体的某一个网站
    ④ location{}标签主要用于匹配网站具体URL路径**

    4. Nginx搭建web网站

    4.1 配置nginx配置文件

    [root@web01 ~]# cat /etc/nginx/conf.d/game.conf 
    server {
            listen 80;
            server_name game.oldboy.com;
    
            location / {
                    root /data;
                    index index.html;
            }   
    }
    

    4.2 放置游戏源代码文件至nginx配置文件root指定的目录

    [root@web01 ~]# mkdir /data && cd /data
    [root@web01 data]# rz html5.zip
    [root@web01 data]# unzip html5.zip
    [root@web01 data]# ll
    total 18848
    drwxr-xr-x 23 root root     4096 Mar  5  2015 ceshi
    drwxr-xr-x 42 root root     4096 Mar  5  2015 game
    -rw-r--r--  1 root root 19248295 Jan 17  2019 html5.zip
    drwxr-xr-x  2 root root     4096 Mar  5  2015 img
    -rwxr-xr-x  1 root root    30312 Mar  5  2015 index.html
    drwxrwxr-x  5 root root      124 Dec  9  2018 __MACOSX
    -rwxr-xr-x  1 root root      578 Mar  5  2015 readme.txt
    [root@web01 data]#
    

    4.3 检查nginx语法是否存在错误

    [root@web01 data]# nginx -t
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    

    4.4 重新加载nginx [ reload | restart ]

    [root@web01 data]# systemctl restart nginx
    

    4.5 配置hosts访问域名

    10.0.0.7  game.oldboy.com
    

    5. Nginx虚拟主机

    通常在企业中可能会有很多业务系统,那么多套业务服务如何使用nginx配置?

    -c

    如果使用如上方式部署,则需要多台服务器配置nginx,但如果使用虚拟主机方式,则在同一个nginx上运行多套单独服务,这些服务是相互独立的,简单来说,看似多套业务系统,实则可以运行在一台nginx服务上

    -c

    5.1 Nginx虚拟主机Nginx配置虚拟主机有三种方式:

    方式一:基于主机多IP方式方式二:基于端口的配置方式方式三:基于多个hosts名称方式(多域名方式)

    5.2 基于多IP的虚拟主机配置实战

    -c

    基于多IP的方式,有如下两种方式:

    -c

    5.2.1 配置多网卡多IP的方式

    样板:
    server {
        ...
        listen 10.0.0.10:80;
        ...
    }
    
    server {
        ...
        listen 10.0.0.11:80;
        ...
    }
    
    实例:
    #1.修改nginx配置
    [root@web01 ~]# cat /etc/nginx/conf.d/ip.conf 
    server {
            listen 10.0.0.7:80;
            server_name _;
    
            location / {
                    root /code_ip_eth0;
                    index index.html;
            }
    }
    
    server {
            listen 172.16.1.7:80;
            server_name _;
    
            location / {
                    root /code_ip_eth1;
                    index index.html;
            }
    }
    
    #2.创建配置指定目录
    [root@web01 ~]# echo "Eth0" > /code_ip_eth0/index.html
    [root@web01 ~]# echo "Eth1" > /code_ip_eth1/index.html
    
    #3.重启nginx服务
    [root@web01 ~]# systemctl restart nginx
    
    #4.使用curl命令测试访问
    [root@web01 ~]# curl 10.0.0.7
    Eth0
    [root@web01 ~]# curl 172.16.1.7
    Eth1
    [root@web01 ~]#
    

    5.2.2 配置单网卡多IP的方式(没必要)

    #添加一个IP
    [root@web01 ~]# ip addr add 10.0.0.11/24 dev eth0
    
    #虚拟机配置方案
    [root@web01 ~]# cat /etc/nginx/conf/conf.d/addr1.conf
    server {
            ...
            listen 10.0.0.7:80;
            ...
    }
    
    [root@web01 ~]# cat /etc/nginx/conf/conf.d/addr2.conf
    server {
            ...
            listen 10.0.0.11:80;
            ...
    }
    

    5.3 基于端口的虚拟主机配置实战

    样板:
    server {
        ...
        listen 81;
        ...
    }
    
    server {
        ...
        listen 82;
        ...
    }
    
    实例:
    #1.修改nginx配置
    [root@web01 ~]# cat /etc/nginx/conf.d/port.conf 
    server {
            listen 81;
    
            location / {
                    root /code_81;
                    index index.html;
            }
    } 
    
    server {
            listen 82;
    
            location / {
                    root /code_82;
                    index index.html;
            }   
    } 
    
    #2.创建指定目录并写入文件
    [root@web01 ~]# mkdir /code_8{1..2}
    [root@web01 ~]# echo "81" > /code_81/index.html
    [root@web01 ~]# echo "82" > /code_82/index.html
    
    #3.重启nginx服务
    [root@web01 ~]# nginx -t
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    [root@web01 ~]# systemctl restart nginx
    
    #浏览器访问测试
    10.0.0.7:81
    10.0.0.7:82
    

    5.4 基于多个hosts的虚拟主机配置实战

    样板:
    server {
        ...
        listen 80;
        server_name test1.oldboy.com;
        ...
    }
    
    server {
        ...
        listen 80;
        server_name test2.oldboy.com;
        ...
    }
    
    实例:
    #1.添加多主机nginx配置文件
    [root@web01 ~]# cat /etc/nginx/conf.d/test1.oldboy.com.conf 
    server {
            listen 80;
            server_name test1.oldboy.com;
    
            location / {
                    root /code/test1;
                    index index.html;
            } 
    }
    [root@web01 ~]# cat /etc/nginx/conf.d/test2.oldboy.com.conf 
    server {
            listen 80;
            server_name test2.oldboy.com;
    
            location / {
                    root /code/test2;
                    index index.html;
            }
    }
    [root@web01 ~]#
    
    #2.创建指定目录并写入文件
    [root@web01 ~]# mkdir /code/test{1..2}
    [root@web01 ~]# echo "test1_server" > /code/test1/index.html
    [root@web01 ~]# echo "test2_server" > /code/test2/index.html
    
    #3.重启nginx服务
    [root@web01 ~]# nginx -t
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    [root@web01 ~]# systemctl restart nginx
    
    #配置域名解析 windows下 C:WindowsSystem32driversetchosts
    10.0.0.7  test1.oldboy.com
    10.0.0.7  test2.oldboy.com
    
    #浏览器访问测试
    test1.oldboy.com
    test2.oldboy.com
    

    6. Nginx日志管理

    Nginx有非常流火的日志记录模式,每个级别的配置可以有个字独立的访问日志。日志格式通过log_format命令定义格式。

    6.1 nginx自查

    1.修改完配置记得使用 nginx -t 检查语法
    2.如果没有检查语法,直接重载导致报错。systemctl status nginx -l 查看错误信息

    6.2 配置语法: 包括: error.log access.log

    log_format命令定义日志格式语法

    Syntax: log_format name [escape=default|json] string ...;
    Default: log_format combined "...";
    Context: http

    6.3 Nginx默认定义语法

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    

    6.4 Nginx日志格式允许包含的内置变量

    $remote_addr            #表示客户端地址
    $remote_user            #http客户端请求nginx认证用户名
    $time_local             #Nginx的时间
    $request                #Request请求行, GET等方法、http协议版本
    $status                 #respoence返回状态码
    $body_bytes_sent        #从服务端响应给客户端body信息大小
    $http_referer           #http上一级页面, 防盗链、用户行为分析
    $http_user_agent        #http头部信息, 客户端访问设备
    $http_x_forwarded_for   #http请求携带的http信息
    
    $time_iso8601           #记录ISO8601标准格式下的本地时间
    $bytes_sent             #发送给客户端的总字节数
    $msec                   #日志写入时间,单位为秒,精度是毫秒
    $request_length         #请求的长度(包括请求行,请求头和请求正文)
    $request_time           #请求话费的时间,单位为秒,精度毫秒
    # 注:如果Nginx位于负载均衡器,nginx反向代理之后,web服务器无法直接获取到客户端真是的IP地址。
    # $remote_addr 获取的是反向代理的IP地址;反向代理服务器在转发请求的http头信息中。
    # 增加X-Forwarded-For信息,用来记录客户端IP地址和客户端请求的服务器地址。
    

    6.5 access_log日志配置语法

    官网语法格式

    Syntax: access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
    access_log off;
    Default: access_log logs/access.log combined;
    Context: http, server, location, if in location, limit_except
    

    6.6 nginx access_log日志配置实践

    server {
            listen 80;
            server_name code.oldboy.com;
    
            #将当前的server网站的访问日志记录至对应的目录,使用main格式
            access_log /var/log/nginx/code.oldboy.com.log main;
            location / {
                    root /code;
            }
    
            #当有人请求改favicon.ico时,不记录日志
            location /favicon.ico {
                    access_log off;
                    return 200;
            }
    }               
    

    6.7 nginx 日志切割logrotate

    [root@web01 ~]# cat /etc/logrotate.d/nginx 
    /var/log/nginx/*.log {
            daily                       #每天切割日志
            missingok                   #日志丢失忽略
            rotate 52                   #日志保留52天
            compress                    #日志文件压缩
            delaycompress               #延迟压缩日志
            notifempty                  #不切割空文件
            create 640 nginx adm        #日志文件权限
            sharedscripts
            postrotate                  #切割日志执行的命令
                    if [ -f /var/run/nginx.pid ]; then
                            kill -USR1 `cat /var/run/nginx.pid`
                    fi
            endscript
    }
    [root@web01 ~]#
    

    6.8 nginx 日志切割后效果

    [root@web01 ~]# cd /var/log/nginx/
    [root@web01 nginx]# ll
    total 20
    -rw-r----- 1 nginx adm  3162 Jul 31 21:27 access.log
    -rw-r----- 1 nginx adm   410 Jul 30 17:41 access.log-20190731
    -rw-r----- 1 nginx adm  2036 Jul 31 21:33 error.log
    -rw-r----- 1 nginx adm   246 Jul 30 17:41 error.log-20190731
    -rw-r--r-- 1 root  root 2667 Jul 31 21:33 test1.log
    
  • 相关阅读:
    spring中bean的高级属性之list, set, map以及props元素(含举例)
    Schema约束与DTD约束
    spring中配置Properties对象的方法
    web.xml 中的listener、 filter、servlet 加载顺序及其详解
    MySql为某个表增加rownumber
    分组取前N记录(转)
    1、Spring MVC的web.xml配置详解(转)
    Spring的PropertyPlaceholderConfigurer应用(转)
    几种任务调度的 Java 实现方法与比较(定时任务)(转)
    Spring定时任务的几种实现(转)
  • 原文地址:https://www.cnblogs.com/chenmiao531759321/p/11436064.html
Copyright © 2020-2023  润新知