Loading

Nginx部署及Web基础

Web服务

Web服务就是B/S架构,Web服务器常常以B/S(Browser/Server)方式提供服务,浏览器和服务器的交互方式。

Web服务器软件

Web服务器常用的有Apache和Nginx,两者都实现了HTTP 1.1协议,两者的优缺点如下文(写的相当详细了):

  • Nginx和Apache对比图

    image
    image
    image
    image

Nginx简介

Nginx是一个开源且高性能、可靠的http web服务、代理服务

  • 开源:直接获取源代码
  • 高性能:支持海量开发
  • 可靠:服务稳定

Nginx特点

  • 高性能,高并发:nginx支持很高的并发,nginx在处理大量并发的情况下比其他web服务要快
  • 轻量且高扩展:功能模块少,只保留核心模块,其他代码模块化,需要什么模块再安装模块,不需要全部安装,并且还支持第三方模块
  • 高可靠性:几乎不会出现问题,其他的web服务需要每隔一段时间进行重启,nginx不需要,nginx的宕机时间,是99999级别
    支持多路复用
  • 支持热部署: Nginx支持热部署,它的自动特别容易,几乎可以7天*24小时不间断的运行,即使,运行数个月也不需要重新启动,还能够在不间断服务的情况下,对软件版本进行升级。
  • Nginx使用的网络模型是Epool

网络模型:select、poll、epoll

安装Nginx

  • yum安装

    • http://nginx.org/en/linux_packages.html#Ubuntu
      image

    • 1.创建官网指定文件目录

      [root@web01 ~]# vim /etc/yum.repos.d/nginx.repo
      # 将上述官网内容拷贝到这个文件中
      # 我已经拷贝好了👇,拷贝到文档中在插入模式粘贴
      [nginx-stable]
      name=nginx stable repo
      baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
      gpgcheck=1
      enabled=1
      gpgkey=https://nginx.org/keys/nginx_signing.key
      module_hotfixes=true
      
      [nginx-mainline]
      name=nginx mainline repo
      baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
      gpgcheck=1
      enabled=0
      gpgkey=https://nginx.org/keys/nginx_signing.key
      module_hotfixes=true
      
    • 2.安装Nginx

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

      image

    • 3.启动nginx

      # 如果开启了httpd请关闭服务,再打开nginx
      [root@web01 ~]# systemctl stop httpd
      [root@web01 ~]# systemctl start nginx
      

      image

  • 编译安装

    1.获取文件
    [root@web01 ~]#  wget https://nginx.org/download/nginx-1.20.2.tar.gz
    
    2.解压
    [root@web01 ~]# tar -xf nginx-1.20.2.tar.gz
    
    3.预处理
    [root@web01 nginx-1.20.2]# ./configure
    
    4.编译安装
    [root@web01 nginx-1.20.2]# make
    [root@web01 nginx-1.20.2]# make install
    
    5.安装好后,目录/usr/local下就会多了nginx目录
    启动
    /usr/local/nginx/sbin/nginx
    关闭服务
    /usr/local/nginx/sbin/nginx -s stop
    systemctl stop nginx
    

平滑增加Nginx模块

平滑增加Nginx模块必须是编译安装的模式,因为yum安装会自动安装模块,无法指定,切换到web02做示例:

  • 在web02虚拟机中编译安装nginx
    [root@web02 ~]# wget https://nginx.org/download/nginx-1.20.2.tar.gz
    [root@web02 ~]# tar -xf nginx-1.20.2.tar.gz
    [root@web02 nginx-1.20.2]# ./configure
    [root@web02 nginx-1.20.2]# make
    [root@web02 nginx-1.20.2]# make install
    
    # 补充:如果使用编译安装nginx查看版本,不能直接使用nginx -v,因为没有环境变量,必须切换到/usr/local/nginx/sbin目录下,这个目录下的nginx是可执行的
    [root@web02 sbin]# /usr/local/nginx/sbin/nginx -v
    nginx version: nginx/1.20.2
    
  • 查看模块
    [root@web02 sbin]# /usr/local/nginx/sbin/nginx -V
    nginx version: nginx/1.20.2
    built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
    configure arguments:
    # 没有模块,重新编译增加模块
    
  • 重新编译增加模块
    # 如果解压过,删除重新解压编译安装
    [root@web02 ~]# rm -rf nginx-1.20.2
    [root@web02 ~]# tar -xf nginx-1.20.2.tar.gz 
    [root@web02 ~]# cd nginx-1.20.2
    # 查看要增加的模块名
    [root@web02 nginx-1.20.2]# ./configure --help
    # 增加模块--with-http_ssl_module
    [root@web02 nginx-1.20.2]#./configure  --with-http_ssl_module
    # 如果报错:./configure: error: SSL modules require the OpenSSL library.就安装openssl,没有就继续安装
    [root@web02 nginx-1.20.2]# yum install openssl openssl-devel -y 
    # 重新增加
    [root@web02 nginx-1.20.2]# ./configure  --with-http_ssl_module
    # 编译安装
    [root@web02 nginx-1.20.2]# make
    [root@web02 nginx-1.20.2]# make install
    # 安装好后,目录/usr/local下就会多了nginx目录
    启动
    /usr/local/nginx/sbin/nginx
    关闭服务
    /usr/local/nginx/sbin/nginx -s stop
    systemctl stop nginx
    
  • 查看是否增加模块
    [root@web02 local]# /usr/local/nginx/sbin/nginx -V
    nginx version: nginx/1.20.2
    built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
    built with OpenSSL 1.0.2k-fips  26 Jan 2017
    TLS SNI support enabled
    configure arguments: --with-http_ssl_module
    # 增加成功
    

Nginx的命令

安装成功后输入nginx -h查看所有参数

[root@web01 nfs]# nginx -h
nginx version: nginx/1.20.2
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
             [-e filename] [-c filename] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /etc/nginx/)
  -e filename   : set error log file (default: /var/log/nginx/error.log)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file
  • -v:打印版本号

    [root@web01 nfs]# nginx -v
    nginx version: nginx/1.20.2
    
  • -V:打印版本和配置项

    [root@web01 nfs]# nginx -V
    nginx version: nginx/1.20.2
    built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (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'
    
  • -t:检查配置文件

    [root@web01 nfs]# nginx -t
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    
  • -T:测试配置文件并运行

    [root@web01 nfs]# nginx -T
    
  • -q:打印错误日志

    [root@web01 nfs]# nginx -q
    
  • -s : 操作进程

    stop	:停止
    quit	:退出
    reopen	:重启
    reload	:重载
    nginx -s stop #强制停止Nginx服务
    nginx -s quit #优雅地停止Nginx服务(即处理完所有请求后再停止服务)
    nginx -s reopen #重启Nginx
    nginx -s reload #重新加载Nginx配置文件,然后以优雅的方式重启Nginx
    
  • 指定路径参数

    -p : 指定nginx的工作目录
    -e : 指定错误日志路径
    -c : 指定配置文件的路径
    nginx -p prefix #设置前缀路径(默认是:/usr/share/nginx/)
    nginx -e logfile # 设置错误日志路径(默认是:/var/log/nginx/error.log)
    nginx -c filename #设置配置文件(默认是:/etc/nginx/nginx.conf)
    
  • -g : 设置一个全局的Nginx配置项

    [root@web01 ~]# nginx -g 'daemon off;'
    

Nginx配置文件

image

nginx分为全局配置和模块配置

  • 相关文件:/etc/nginx/nginx.conf

image

配置文件内容

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}
  • 全局配置

    • user:指定Nginx的启动用户
    • worker_processes:定义Nginx的worker进程数,auto相当于CPU的数量(auto可以修改为整数)
    • error_log:错误日志路径
    • pid:pid的存放文件路径
    • events : 模块配置
      # 可配置项:
      worker_connections:代表每一个worker进程最多同时接入多少个请求(每一个进程处理的请求个数)
      use : 指定Nginx的网络模型;
      
    • http:web服务模块
      include : 加载外部的配置项,降低了文件的复杂度
      default_type : 如果找不到文件的类型,则按照指定默认类型处理
      log_format : 定义日志格式
      日志格式默认为简洁版(main),可以修改为json格式(详细版)
              log_format json '{"@timestamp":"$time_iso8601",'
                        '"host":"$server_addr",'
                        '"service":"nginxTest",'
                        '"trace":"$upstream_http_ctx_transaction_id",'
                        '"log":"log",'
                        '"clientip":"$remote_addr",'
                        '"remote_user":"$remote_user",'
                        '"request":"$request",'
                        '"http_user_agent":"$http_user_agent",'
                        '"size":$body_bytes_sent,'
                        '"responsetime":$request_time,'
                        '"upstreamtime":"$upstream_response_time",'
                        '"upstreamhost":"$upstream_addr",'
                        '"http_host":"$host",'
                        '"url":"$uri",'
                        '"domain":"$host",'
                        '"xff":"$http_x_forwarded_for",'
                        '"referer":"$http_referer",'
                        '"status":"$status"}';
      access_log /var/log/nginx/access.log json ;
      
      sendfile : 高效读取文件
      keepalive_timeout : 长连接保持连接的
      # timeout不能太低,不然和短链接一样
      
  • include: 加载外部的配置项

    相关文件/etc/nginx/conf.d/*.conf

    # 重点
    server : 网址模块,每一个server代表一个网站,可以有多个
    listen : 监听的端口
    server_name : 定义域名
    location {} : 访问路径
    	root : 指定网址路径
    	index : 指定网址的索引文件
    

小游戏案例

  • 超级马里奥

    • 上传代码
      # 源代码百度自己下载的,想要私我就可以了
      # 在/opt/创建存放游戏文件的目录/opt/Super_Mario
      
    • 编辑配置文件
      [root@web01 ~]# cd /etc/nginx/conf.d/
      [root@web01 conf.d]# vim /etc/nginx/conf.d/game.conf 
      server{
          listen 80;
          server_name Mario.test.com;
          location / {
              root /opt/Super_Mario;
              index index.html;
          }
      }
      
    • 测试配置文件是否正常
      [root@web01 conf.d]# nginx -t
      nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
      nginx: configuration file /etc/nginx/nginx.conf test is successful
      
    • 重启Nginx
      [root@web01 conf.d]# systemctl restart nginx
      
    • 域名解析
      在文件 C:\Windows\System32\drivers\etc\hosts中添加ip 和域名
      192.168.15.7 mario.test.com
      
      image
  • 中国象棋

    • 上传游戏文件,并创建存放游戏的目录
      [root@web01 opt]# mkdir chess
      
    • 编辑配置文件
      [root@web01 conf.d]# cd /etc/nginx/conf.d
      [root@web01 conf.d]# vim chess.conf
      server{
          listen 80;
          server_name chess.test.com;
          location / {
              root /opt/chess;
              index index.html;
          }
      }
      
    • 测试配置文件是否正常
      [root@web01 conf.d]# nginx -t
      nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
      nginx: configuration file /etc/nginx/nginx.conf test is successfu
      
    • 重启Nginx
      [root@web01 conf.d]# systemctl restart nginx
      
    • 域名解析
      在文件 C:\Windows\System32\drivers\etc\hosts中添加ip 和域名
      192.168.15.7 mario.test.com chess.test.com
      
      image

补充:解决NFS持久化

  • 方式一

    • 通过开机自启动脚本挂载

      使用方式一,注意开机需要关闭防火墙和selinux

      [root@web01 ~]# vim /etc/rc.local
      /usr/bin/mount -t nfs 172.16.1.31:/web/upload /var/www/html/upload
      [root@web01 ~]# chmod +x /etc/rc.d/rc.local
      
  • 方式二

    • 通过/etc/fstab配置文件

      使用方式二,需要在服务端开启nfs-server服务systemctl start nfs-server

      [root@web02 ~]# vim /etc/fstab
      172.16.1.31:/web/upload  /var/www/html/upload   nfs       defaults          0                0
      # 测试是否挂载成功,不报错就是挂载成功了!
      [root@web02 ~]# mount -a
      # 修改文件的格式内容如下图
      
      image

nginx虚拟主机

  • 基于多IP的方式

    # 防止其他配置文件影响,将所有配置文件压缩
    [root@web01 conf.d]# gzip Mario.conf 
    [root@web01 conf.d]# gzip chess.conf.gz 
    [root@web01 conf.d]# gzip default.conf.gz 
    # 编辑配置文件
    [root@web01 ~]# cd /etc/nginx/conf.d
    [root@web01 conf.d]# vim game.conf 
    server {
        listen 80;
        server_name 192.168.15.7;
        location / {
        root /opt/Super_Mario;
            index index.html;
        }
    }
    server {
        listen 80;
        server_name 172.16.1.7;
        location / {
            root /opt/chess;
            index index.html;
        }
    }
    
    # 测试配置文件
    [root@web01 conf.d]# nginx -t
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successfu
    # 重启服务
    [root@web01 conf.d]# systemctl restart nginx
    
  • 基于多端口的方式

    # 编辑配置文件
    [root@web01 conf.d]# vim game1.conf 
    server {
        listen 80;
        server_name 192.168.15.7;
        location / {
            root /opt/Super_Mario;
            index index.html;
        }
    }
    server {
        listen 81;
        server_name 192.168.15.7;
        location / {
            root /opt/chess;
            index index.html;
        }
    }
    ~
    
  • 基于多域名的方式

    # 编辑配置文件
    [root@web01 conf.d]# vim game2.conf
    server {
        listen 80;
        server_name www.Super_Mario.com;
        location / {
            root /opt/Super_Mario;
            index index.html;
        }
    }
    server {
        listen 80;
        server_name www.chesss.com;
        location / {
            root /opt/chess;
            index index.html;
        }
    }
    # 注意域名不能用chess
    

Nginx日志

  • nginx日志文件目录:/var/log/nginx/
  • 排错方式:
    • 网站排错
    • 查看错误日志
      # 原有日志格式,不能注释或者去掉
          log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '"$http_user_agent" "$http_x_forwarded_for" $request_time';
          # json日志格式
          log_format log_json '{"@timestamp": "$time_local", '
                              '"remote_addr": "$remote_addr", '
                              '"referer": "$http_referer", '
                              '"request": "$request", '
                              '"status": $status, '
                              '"bytes": $body_bytes_sent, '
                              '"agent": "$http_user_agent", '
                              '"x_forwarded": "$http_x_forwarded_for", '
                              '"up_addr": "$upstream_addr",'
                              '"up_host": "$upstream_http_host",'
                              '"up_resp_time": "$upstream_response_time",'
                              '"request_time": "$request_time"'
                              ' }';
      
          access_log  logs/access.log log_json; # 引用日志格式名称
      

Nginx配置文件配置项

  • 相关文件:/etc/nginx/nginx.conf
  • 主要配置项
    # 配置详解
    $remote_addr:客户端IP
    - :分隔符
    $remote_user:代表登录用户(没有就是-)
    [$time_local] :访问时间
    $request:请求方式、类型
    $status :状态码
    $body_bytes_sent :访问文件大小
    $http_referer:访问域名 
    $http_user_agent:客户端标识
    $http_x_forwarded_for:真实的客户端IP(在反向代理中生效)
    

Nginx模块

  • Nginx访问控制模块

    官网介绍http://nginx.org/en/docs/
    • ngx_http_access_module模块

      使用范围:http,server,location,limit_except(http,server常用)

      # 配置项:deny和allow,拒绝或者允许某些ip访问
      deny:拒绝
      allow:允许
      # 语法:
      Syntax:	deny address | CIDR | unix: | all;
      Syntax:	allow address | CIDR | unix: | all;
      
      
      # 官网示例:
      location / {
          deny  192.168.1.1;
          allow 192.168.1.0/24;
          allow 10.1.1.0/16;
          allow 2001:0db8::/32;
          deny  all;
      }
      # 示例1:
      允许192.168.15.1访问,不允许其他IP访问
      # 修改game2.conf文件中的server
      server {
          listen 80;
          server_name www.Super_Mario.com;
          allow 192.168.15.1;
          deny all;
          location / {
              root /opt/Super_Mario;
              index index.html;
          }
      }
      
      # 示例2:
      允许192.168.15.0这个网段访问,不允许其他网段访问
      allow 192.168.15.0/24;
      deny all;
      # 示例3:
      只允许通过VPN来访问
      allow 172.16.1.81;
      deny all;
      
    • ngx_http_auth_basic_module认证模块

      使用范围:http,server,location,limit_except

      语法:auth_basic string | off;(默认关闭)
      # 官网示例:
      location / {
          auth_basic           "closed site";
          auth_basic_user_file conf/htpasswd;
      }
      
      # 示例:访问之前需要登录
      # 安装httpd-tools
      # ubuntu 安装  apt install apache2-utils
      [root@web01 conf.d]# yum install httpd-tools -y
      # 生成用户名密码文件
      [root@web01 conf.d]# htpasswd -c /etc/nginx/auth hammer
      New password: 
      Re-type new password: 
      Adding password for user hammer
      #  查看
      [root@web01 conf.d]# cat /etc/nginx/auth 
      hammer:$apr1$fOHr21Vf$zpI/MVxQ452KzP0p10QI10
      # 将密码文件路径加入配置
      server {
          listen 80;
          server_name www.Super_Mario.com;
          auth_basic "hello nginx";
          auth_basic_user_file /etc/nginx/auth;
          location / {
              root /opt/Super_Mario;
              index index.html;
          }
      }
      [root@web01 conf.d]# 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 conf.d]# systemctl restart nginx
      

      image

    • ngx_http_autoindex_module目录索引模块

      使用范围:http,server,location

      语法:autoindex on | off(默认关闭);
      # 官网示例
      location / {
          auth_basic "登录认证";
          auth_basic_user_file /etc/nginx/auth;
          autoindex on;
          autoindex_exact_size off;
          autoindex_localtime on;  # 本地时间
      }
      
      # 示例:指定目录索引展示
      [root@web01 games]# cd /etc/nginx/conf.d/
      [root@web01 conf.d]# vim index.conf
      
  • Nginx状态监控模块

    # stub_status需要一个独立的location
    # 监控Nginx运行状态。
    [root@web01 conf.d]# vim index.conf 
    server {
        listen 80;
        server_name 192.168.15.7;
        location / {
            stub_status;
        }
    }
    
  • 访问连接控制模块

    1、控制Nginx连接数
    
    安装ab测试命令
        yum install httpd-tools -y
    
    ab 参数
            -n : 总共需要访问多少次
            -c : 每次访问多少个
    [root@web01 conf.d]ab -n 10000 -c http://50 192.168.1.1/
    
    [root@web01 conf.d]# vim game5.conf 
    # limit_req_zone $remote_addr zone=one:10m rate=1r/s;
    limit_conn_zone $remote_addr zone=addr:10m;
    server {
        listen 80;
        server_name 192.168.15.7;
        # limit_req zone=one burst=5;
        limit_conn addr 1;
        location / {
            root /opt/Super_Marie;
            index index.html;
        }
    }
    
    2、控制Nginx访问量
    
        1、连接池
            limit_req_zone $remote_addr zone=one:10m rate=1r/s;
            声明连接池       变量          名称  连接池的大小  速率
        2、限制数
    
    案例1:要求每秒只能有一个访问。
    [root@web01 conf.d]# vim game5.conf 
    limit_req_zone $remote_addr zone=one:10m rate=1r/s;
    server {
        listen 80;
        server_name 192.168.15.7;
        limit_req zone=one burst=5;
        location / {
            root /opt/Super_Marie;
            index index.html;
        }
    }
    
  • Location配置项

    使用Nginx Location可以控制访问网站的路径, 但一个server可以有多个location配置, 多个location的优先级该如何区分。

    • location匹配符号

      匹配符 匹配规则 优先级
      = 精确匹配 1
      ^~ 以某个字符串开头 2
      ~ 区分大小写的正则匹配 3
      ~* 不区分大小写的正则匹配 3
      / 通用匹配,任何请求都会匹配到 4
      server {
          listen 80;
          server_name _;
         
          location ~* /python {
              default_type text/html;
              return 200 "Location ~*";
          }
      
          location ~ /Python {
              default_type text/html;
              return 200 "Location ~";
          }
      
          location ^~ /python {
              default_type text/html;
              return 200 "Location ^~";
          }
      
          location = /python {
              default_type text/html;
              return 200 "Location =";
          }
      }
      
posted @ 2022-10-07 20:57  爱learn  阅读(56)  评论(0编辑  收藏  举报