Nginx网站服务

编程知识 更新时间:2023-04-23 08:40:42

目录

  • Nginx服务介绍
    • Nginx软件概念
    • Nginx软件特点
    • Nginx企业应用
  • Nginx服务部署
    • nginx软件安装
      • yum安装软件
      • 编译安装软件
    • nginx目录结构
    • nginx配置文件
      • /etc/nginx/nginx.conf
      • /etc/nginx/conf.d/default.conf
  • Nginx网站搭建
    • 利用nginx服务搭建一个网站
      • 编写虚拟主机配置文件
      • 站点目录放置网站代码
      • 重启nginx服务(平滑重启)
      • 配置DNS解析记录信息
      • Win浏览器访问测试
      • 搭建网站常见错误
    • 利用nginx服务搭建多个网站
      • 编写多个虚拟主机配置文件
      • 站点目录放置网站代码
      • 重启nginx服务(平滑重启)
      • 配置DNS解析记录信息
      • Win浏览器访问测试
    • 企业中虚拟主机的访问
      • 企业中虚拟主机的访问方式
        • 基于域名
        • 基于地址
        • 基于端口
      • 企业中网站的页面访问原理
      • 企业中网站的安全访问配置
        • 根据用户访问的地址进行控制(ngx_http_access_module)
        • 根据用户访问进行认证(ngx_http_auth_basic_module)
  • Nginx企业应用
    • 利用nginx服务搭建配置文件别名功能
    • 利用nginx服务搭建网站文件共享服务器
      • 模块
      • 网站页面目录索引
      • 网站页面字符修改
    • 利用nginx状态模块功能对网站进行监控
      • 模块
      • 实践
    • nginx日志功能配置
      • 错误日志
      • 访问日志
      • 自定义网站访问日志
    • nginx服务location作用
      • 网站优雅显示
      • 网站服务匹配
        • location详细配置
        • location匹配实战
    • nginx实现页面跳转功能
      • 模块
      • 实践


Nginx服务介绍

Nginx软件概念

Nginx是一个开源的、支持高性能、高并发的www服务器和代理服务软件。Nginx可以运行在Unix、Linux、BSD、Mac OS X,以及Windows等操作系统中。Nginx因具有高并发(特别是静态资源)、占用系统资源少等特性,且功能丰富而逐渐流行起来。

在功能应用方面,Nginx不但是一个优秀的Web服务软件,还具有反向代理负载均衡功能和缓存服务功能。在反向代理负载均衡功能方面,它类似于大名鼎鼎的LVS负载均衡及Haproxy等专业代理软件,但Nginx部署起来更为简单、方便;在缓存服务功能方面,它又类似于Squid等专业的缓存服务软件。

Nginx软件特点

  • 支持高并发,消耗内存资源小;
  • 具有多种功能:网站Web服务功能(Apache)、网站负载均衡功能(LVS)、网站缓存服务功能(Squid);
  • 在多种系统平台都可以进行部署;
  • 实现网络通讯使用异步网络IO模型:epoll模型。
    指标Apache selectNginx epoll
    随着连接数的增加性能急剧下降,处理成千上万并发连接数时性能很差随着连接数的增加,性能基本没有下降,处理成千上万并发连接数时性能很好
    连接数连接数有限制,处理最大连接数不超过1024,如果需要处理的连接数超过1024个,则需要修改FD_SETSIZE宏,并重新编译连接数无限制
    内在处理机制线性轮询回调callback
    开发复杂性

Nginx企业应用

  1. 作为Web服务软件
    Nginx是一个支持高性能、高并发的Web服务软件,它具有很多优秀的特性,作为Web服务器,Nginx比Apache能够支持更多的并发连接访问,占用的资源却更少,效率更高。

  2. 反向代理或负载均衡服务
    Nginx可以作为Web服务、、PHP等动态服务及Memcached缓存的代理服务器,它具有类似专业反向代理软件(如Haproxy)的功能,同时也是一个优秀的邮件代理服务软件。

  3. 前端业务数据缓存服务
    Nginx可以通过自身的proxy_cache模块实现类Squid等专业缓存软件的功能。

Nginx服务部署

nginx软件安装

yum安装软件

使用官方yum源安装的是最新版本,软件目录结构比较标准;
使用非官方yum源进行安装的不是最新版本,目录结构会发生变化。

  1. 更新nginx官方yum源

    yum官方下载地址

    拉到网址最下面找到Linux Package

    点击RHEL/CentOS版本

    根据帮助文档进行操作(设置稳定版本的yum源)

    [root@web01 ~]# vim /etc/yum.repos.d/nginx.repo
    [root@web01 ~]# cat /etc/yum.repos.d/nginx.repo
    [nginx-stable]
    name=nginx stable repo
    baseurl=http://nginx/packages/centos/$releasever/$basearch/
    gpgcheck=1
    enabled=1
    gpgkey=https://nginx/keys/nginx_signing.key
    module_hotfixes=true
    
  2. yum安装nginx软件

    [root@web01 ~]# yum install -y nginx
    
  3. 启动nginx服务

    [root@web01 ~]# systemctl start nginx
    
  4. 访问IP,查看nginx是否正确安装

编译安装软件

  1. 下载nginx安装包

    [root@web01 ~]# wget http://nginx/download/nginx-1.20.1.tar.gz
    

    解决软件依赖,如果事先不知道软件依赖,直接进行安装,根据错误提示判断软件依赖包。

  2. 解压下载好的软件,并进入软件目录

    [root@web01 tools]# tar -xf nginx-1.20.1.tar.gz 
    [root@web01 tools]# ls
    nginx-1.20.1  nginx-1.20.1.tar.gz
    [root@web01 tools]# cd nginx-1.20.1/
    [root@web01 nginx-1.20.1]# ls
    CHANGES  CHANGES.ru  LICENSE  README  auto  conf  configure  contrib  html  man  src
    
  3. 编译安装三部曲(./configure、make、make install)

    [root@web01 nginx-1.20.1]# ./configure
    [root@web01 nginx-1.20.1]# make
    [root@web01 nginx-1.20.1]# make install
    

nginx目录结构

  • /etc/nginx/:配置文件目录

  • /var/log/nginx/:日志文件目录

  • /usr/sbin/nginx:命令文件

  • /usr/share/nginx/html/:站点目录

  • /etc/logrotate.d/nginx :用于日志轮询切割的配置文件
    日志切割方法一:利用脚本实现切割

    #!/bin/bash
    mv /var/log/nginx/access.log /var/log/nginx/access_$(date +%F).log
    systemctl restart nginx

    日志切割方法二:利用专用文件切割程序–logrotate

    vim /etc/logrotate.conf
    # rotate log files weekly
    weekly                     --- 定义默认日志切割的周期
           
    # keep 4 weeks worth of backlogs
    rotate 4                   --- 定义只保留几个切割后的文件
           
    # create new (empty) log files after rotating old ones
    create                     --- 创建出一个相同的源文件
           
    # use date as a suffix of the rotated file
    dateext                    --- 定义角标(扩展名称信息)
           
    # uncomment this if you want your log files compressed
    #compress                  --- 是否对切割后的文件进行压缩处理
           
    # RPM packages drop log rotation information into this directory
    include /etc/logrotate.d   --- 加载包含/etc/logrotate.d/目录中文件配置
           
    # no packages own wtmp and btmp -- we'll rotate them here
    /var/log/wtmp {            --- 单独对某个文件进行切割配置
        monthly
        create 0664 root utmp
        minsize 1M             --- 最小大小为1M,小于1M不进行切割              
        rotate 1
    }
           
    /var/log/btmp {
        missingok
        monthly
        create 0600 root utmp
        rotate 1
    }
    

nginx配置文件

/etc/nginx/nginx.conf:主配置文件
/etc/nginx/conf.d/default.conf:扩展配置文件(虚拟主机)

/etc/nginx/nginx.conf

# 第一部分:主区域配置
user  nginx;     # 定义worker进程管理的用户,用户映射
worker_processes  auto;     # 定义有几个worker进程(进程数最好等于CPU核数)
    # nginx进程:
    # master process:主进程,管理服务是否正常运行
    # worker process:工作进程,处理用户的访问请求
error_log  /var/log/nginx/error.log notice;    # 定义错误日志路径信息
pid        /var/run/nginx.pid;    # 定义pid文件路径信息

# 第二部分:事件区域
events {
    worker_connections  1024;    # 一个worker进程可以同时接受1024访问请求
}

# 第三部分:http区域
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;    # 加载配置文件
}

/etc/nginx/conf.d/default.conf

[root@web01 nginx]# vim /etc/nginx/conf.d/default.conf 
server {
    listen       80;    # 指定监听的端口
    server_name  localhost;    # 指定网站域名 
    location / {
        root   /usr/share/nginx/html;    # 定义站点目录的位置
        index  index.html index.htm;    # 定义首页文件
    }
    error_page   500 502 503 504  /50x.html;    # 优雅显示页面信息
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Nginx网站搭建

利用nginx服务搭建一个网站

编写虚拟主机配置文件

[root@web01 ~]# vim /etc/nginx/conf.d/www.conf

server {
    listen      80;
    server_name www.hello;
    locatiion / {
        root /usr/share/nginx/html;
        index hello.html;
    }
}

站点目录放置网站代码

[root@web01 ~]# cd /usr/share/nginx/html/
[root@web01 html]# vim hello.html

<html>
        <meta charset="utf-8">
        <head>
        <title>Hello,world!</title>
        </head>
        <body>
        Let's begin!
        </body>
</html>

重启nginx服务(平滑重启)

  1. systemctl reload nginx:yum安装重启方式
  2. nginx -s reload:源码安装重启方法

nginx命令参数

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit 				
  -- nginx -t 检查配置文件语法是否正确
  -T            : test configuration, dump it and exit		
  -- nginx -T -- 对配置语法进行检查,并且将所有配置信息显示到屏幕上
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload  
  -- nginx -s reload 控制服务停止或者重新启动
  -p prefix     : set prefix path (default: /etc/nginx/)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file

检查配置文件语法并重启nginx服务

[root@web01 html]# 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 html]# systemctl reload nginx

配置DNS解析记录信息

  • 真实域名:在阿里云上进行DNS解析记录配置
  • 模拟配置:在Windows主机的hosts文件中进行配置即可
    编辑C:\Windows\System32\drivers\etc\hosts文件加入DNS解析记录

Win浏览器访问测试

浏览器进行测试

搭建网站常见错误

网站服务配置文件编写不正确:

  • 404 错误
    解决方法一: 修改nginx配置文件—location(/为默认匹配,匹配站点目录);
    解决方法二: 在站点目录中创建相应目录或文件数据信息。
  • 403 错误
    可能原因:设置禁止访问;
    可能原因:没有首页文件。
  • 500 Internal Server Error
    可能原因:内部程序代码编写有问题;
    可能原因:程序服务中文件权限不正确。

nginx配置文件修改后, 重启服务后才能生效(注意:站点目录中代码文件信息修改,无需重启服务);

DNS信息配置不正确。

利用nginx服务搭建多个网站

编写多个虚拟主机配置文件

编写www网站配置文件

[root@web01 conf.d]# vim www.conf

server {
    listen      80;
    server_name www.hello;
    location / {
        root /usr/share/nginx/html/www;
        index index.html;
    }
}

编写bbs网站配置文件

[root@web01 conf.d]# vim bbs.conf

server {
    listen	80;
    server_name	bbs.hello;
    location / {
        root /usr/share/nginx/html/bbs;
        index index.html;
    }
}

编写blog网站配置文件

[root@web01 conf.d]# vim blog.conf 

server {
    listen      80;
    server_name blog.hello;
    location / {
        root /usr/share/nginx/html/blog;
        index index.html;
    }
}

创建各网站站点目录

[root@web01 conf.d]# mkdir /usr/share/nginx/html/{www,bbs,blog}

站点目录放置网站代码

[root@web01 html]# for name in {www,bbs,blog}; do echo "10.0.0.7 $name.hello" >./$name/index.html ; done
[root@web01 html]# for name in {www,bbs,blog}; do cat ./$name/index.html; done
10.0.0.7 www.hello
10.0.0.7 bbs.hello
10.0.0.7 blog.hello

重启nginx服务(平滑重启)

[root@web01 html]# 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 html]# systemctl reload nginx

配置DNS解析记录信息

编辑Windows的hosts文件

10.0.0.7 www.hello bbs.hello blog.hello

Win浏览器访问测试

www

bbs

blog

企业中虚拟主机的访问

企业中虚拟主机的访问方式

基于域名

注意做好DNS解析,以便能够通过域名正确获得对应的IP地址。

基于地址

  1. 通过地址10.0.0.7访问网站时,如果希望先看到www网站,可以通过编辑nginx配置文件vim /etc/nginx/nginx.conf

  2. 只能用指定地址访问(负载均衡和高可用)

    server {
    listen        10.0.0.7:80;  # 指定IP及端口,重启nginx服务
    server_name   www.hello;
    location  / {
    	root  /usr/share/nginx/html/www;
    	index index.html;
    	}	
    }
    

注意: 配置文件中涉及到地址修改,必须重启nginx服务,不能平滑重启

基于端口

若zabbix服务(apache:80) 与 web服务(nginx:80)安装在同一台主机,由于zabbix默认使用的apache也是80端口,因此这俩服务必须有一个修改端口,不然会产生端口冲突。

server {
listen        8080;  
server_name   www.hello;
location  / {
	root  /usr/share/nginx/html/www;
	index index.html;
	}	
}

企业中网站的页面访问原理

  1. 将域名进行解析 www.hello → 10.0.0.7
  2. 建立TCP连接(传输层协议,端口与端口间建立连接)
  3. 根据应用层HTTP协议发出请求
    请求报文:hosts:www.hello
  4. 倘若没有相同域名的server主机,会找满足端口要求的第一个主机

企业中网站的安全访问配置

根据用户访问的地址进行控制(ngx_http_access_module)

需求:10.0.0.0/24 www.hello/insert/ 不可访问
   172.16.1.0/24 www.hello/insert 可以访问

通过nginx访问模块: ngx_http_access_module实现用户访问地址的控制
ngx_http_access_module官方文档
ngx_http_access_module举例配置

location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

allow指令用法

Syntax:	allow address | CIDR | unix: | all;
Default:	—
Context:	http, server, location, limit_except

deny指令用法

Syntax:	deny address | CIDR | unix: | all;
Default:	—
Context:	http, server, location, limit_except
  1. 创建测试目录和文件

    [root@web01 ~]# cd /usr/share/nginx/html/www/
    [root@web01 www]# mkdir insert   
    [root@web01 www]# echo "Access successful" > insert/access.html
    
  2. 编写配置文件/etc/nginx/conf.d/www.conf

  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 reload nginx 
    
  4. 访问控制测试
    外网测试

    [root@web01 ~]# curl www.hello
    10.0.0.7 www.hello
    [root@web01 ~]# curl www.hello/insert
    <html>
    <head><title>403 Forbidden</title></head>
    <body>
    <center><h1>403 Forbidden</h1></center>
    <hr><center>nginx/1.20.1</center>
    </body>
    </html>
    

    内网测试

    [root@web01 ~]# curl www.hello
    10.0.0.7 www.hello
    [root@web01 ~]# curl www.hello/insert
    <html>
    <head><title>404 Not Found</title></head>
    <body>
    <center><h1>404 Not Found</h1></center>
    <hr><center>nginx/1.20.1</center>
    </body>
    </html>
    

    由于配置文件中匹配insert目录的location只有访问控制的配置,而没有站点目录和网站文件的配置,所以会出现404.解决方式有两种:

    1. 全局配置站点目录和首页文件(location外面为全局配置信息,内部为局部配置信息)
      server {
          listen	80;
          server_name	www.hello;
          root /usr/share/nginx/html/www;
          index index.html;
          location /insert {
              deny 10.0.0.0/24;
              allow 172.16.1.0/24;
          }
      }
      
    2. 在location /insert下配置站点目录和首页文件
      server {
          listen	80;
          server_name	www.hello;
          root /usr/share/nginx/html/www;
          index index.html;
          location /insert {
              deny 10.0.0.0/24;
              allow 172.16.1.0/24;
              root /usr/share/nginx/html/www;
              index index.html;
          }
      }
      

根据用户访问进行认证(ngx_http_auth_basic_module)

通过nginx认证模块: ngx_http_auth_basic_module实现用户访问认证
ngx_http_auth_basic_module官方文档
ngx_http_auth_basic_module举例配置

location / {
    auth_basic           "closed site";   # 开启认证功能
    auth_basic_user_file conf/htpasswd;   # 加载用户密码文件(需要自己创建)
}
  1. 编写虚拟主机配置文件

    [root@web01 ~]# vim /etc/nginx/conf.d/www.conf 
    server {
        listen      80;
        server_name www.hello;
        location / {
            root /usr/share/nginx/html/www;
            index index.html;
            auth_basic      "User authentication";
            auth_basic_user_file ./password/htpasswd;
        }
    }
    
  2. 创建密码文件(文件中密码信息必须是密文的)
    可以使用htpasswd命令创建一个密文信息的密码文件,htpasswd参数说明如下

    [root@web01 yum.repos.d]# htpasswd --help
    Usage:
    	htpasswd [-cimB25dpsDv] [-C cost] [-r rounds] passwordfile username
    	htpasswd -b[cmB25dpsDv] [-C cost] [-r rounds] passwordfile username password
    
    	htpasswd -n[imB25dps] [-C cost] [-r rounds] username
    	htpasswd -nb[mB25dps] [-C cost] [-r rounds] username password
     -c  Create a new file.    # 创建一个密码文件
     -n  Don't update file; display results on stdout.    # 不会更新文件;显示文件信息
     -b  Use the password from the command line rather than prompting for it.    # 免交互方式生成密码信息
     -i  Read password from stdin without verification (for script usage).    # 采用标准输入读取密码,不做验证
     -m  Force MD5 encryption of the password (default).    # 使用md5加密算法(默认)
     -2  Force SHA-256 crypt() hash of the password (secure).    # 使用SHA-256加密算法(安全)
     -5  Force SHA-512 crypt() hash of the password (secure).    # 使用SHA-512加密算法(安全)
     -B  Force bcrypt aencryption of the password (very secure).    # 使用bcrypt aencryption加密算法(非常安全)
     -C  Set the computing time used for the bcrypt algorithm    # 使用bcrypt algorithm加密算法
         (higher is more secure but slower, default: 5, valid: 4 to 31).
     -r  Set the number of rounds used for the SHA-256, SHA-512 algorithms
         (higher is more secure but slower, default: 5000).
     -d  Force CRYPT encryption of the password (8 chars max, insecure).    # 使用CRYPT加密算法
     -s  Force SHA-1 encryption of the password (insecure).    # 使用SHA-1加密算法(不安全)
     -p  Do not encrypt the password (plaintext, insecure).    # 不进行加密
     -D  Delete the specified user.    # 删除指定用户
     -v  Verify password for the specified user.    # 验证指定用户密码
    

    创建用户和密码信息

    [root@web01 password]# htpasswd -bc ./htpasswd letty redhat
    Adding password for user letty
    [root@web01 password]# cat htpasswd 
    letty:$apr1$ntrwDEd0$LvPKg3gtbruDNbut/xpfl.
    

    修改密码文件权限

    [root@web01 password]# ll ./htpasswd 
    -rw-r--r-- 1 root root 44 Aug  6 11:49 ./htpasswd
    [root@web01 password]# chmod 600 ./htpasswd 
    [root@web01 password]# ll ./htpasswd 
    -rw------- 1 root root 44 Aug  6 11:49 ./htpasswd
    

    由于nginx worker进程由www用户管理,任何用户登入网站都会映射为www用户,因此需要将密码文件的所有者设置为www

    [root@web01 password]# chown www.www ./htpasswd 
    [root@web01 password]# ll
    total 4
    -rw------- 1 www www 44 Aug  6 12:06 htpasswd
    
  3. 重启nginx服务

    [root@web01 password]# 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 password]# systemctl reload nginx.service 
    
  4. 访问测试

    [root@web01 password]# curl www.hello 
    <html>
    <head><title>401 Authorization Required</title></head>
    <body>
    <center><h1>401 Authorization Required</h1></center>
    <hr><center>nginx/1.20.1</center>
    </body>
    </html>
    [root@web01 password]# curl www.hello -u letty:redhat
    10.0.0.7 www.hello
    

Nginx企业应用

利用nginx服务搭建配置文件别名功能

网站页面别名功能

作用:

  • 访问测试:使用短域名方便测试
  • 定位要访问的网站服务器:多台服务器时不同的域名方便定位

实践:

  1. 编写配置文件/etc/nginx/conf.d/www.conf
  2. 重启nginx服务
    [root@web01 password]# 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 password]# systemctl reload nginx 
    
  3. 配置DNS解析信息
    [root@web01 password]# vim /etc/hosts
    
    10.0.0.7        www.hello
    10.0.0.7        test
    
  4. 访问测试
    [root@web01 password]# curl www.hello 
    10.0.0.7 www.hello
    [root@web01 password]# curl test
    10.0.0.7 www.hello
    

利用nginx服务搭建网站文件共享服务器

模块

ngx_http_autoindex_module官方文档
ngx_http_autoindex_module使用范例

location / {
    autoindex on;
}

ngx_http_autoindex_module使用说明

Syntax:	autoindex on | off;
Default:	
autoindex off;
Context:	http, server, location

网站页面目录索引

  1. 编写配置文件

    [root@web01 conf.d]# vim www.conf 
    server {
        listen      80;
        server_name www.hello;
        location / {
            root /usr/share/nginx/html/www;
            # index index.html;    # index默认使用index.html,除了注释此处的index,还要移除站点目录下的index.html
            auth_basic      "User authentication";
            auth_basic_user_file password/htpasswd;
            autoindex on;    # 开启nginx站点目录索引功能
        }
    }
    
  2. 重启nginx服务

    [root@web01 conf.d]# nginx -t 
    nginx: [emerg] unknown directive "authindex" in /etc/nginx/conf.d/www.conf:9
    nginx: configuration file /etc/nginx/nginx.conf test failed
    [root@web01 conf.d]# systemctl reload nginx.service
    
  3. 移除首页文件

    [root@web01 www]# cd /usr/share/nginx/html/www
    [root@web01 www]# ls
    index.html  insert
    [root@web01 www]# mv index.html{,.bak}
    [root@web01 www]# ls
    index.html.bak  insert
    
  4. 创建测试数据并进行访问测试
    创建测试数据

    [root@web01 www]# mkdir CentOS{6.7,6.8,6.9,7.0}
    [root@web01 www]# for id in {6.7,6.8,6.9,7.0}; do echo "this is a CentOS $id version, can not be downloaded." > CentOS$id/version.txt; done; 
    [root@web01 www]# for id in {6.7,6.8,6.9,7.0}; do echo "this is a CentOS $id version, can be downloaded." > CentOS$id/version.php; done; 
    

    浏览器测试

    点击version.php自动下载文件
    点击version.txt时显示文件内容
    原因:/etc/nginx/mime.types媒体资源文件中有的扩展名资源,点击可以直接看到数据信息;文件中没有的扩展名资源,点击会直接下载资源。

网站页面字符修改

[root@web01 conf.d]# vim www.conf 
server {
    listen      80;
    server_name www.hello;
    location / {
        root /usr/share/nginx/html/www;
        # index index.html;    
        auth_basic      "User authentication";
        auth_basic_user_file password/htpasswd;
        autoindex on;    
        charset	utf-8;   # 修改目录结构中的中文乱码问题
    }
}

利用nginx状态模块功能对网站进行监控

模块

ngx_http_stub_status_module官方文档
ngx_http_stub_status_module使用范例

location = /basic_status {
    stub_status;
}

ngx_http_stub_status_module使用说明

Syntax:	stub_status;
Default:	—
Context:	server, location

实践

  1. 编写配置文件

    [root@web01 nginx]# vim conf.d/status.conf
    
    server {
        listen	80;
        server_name status;
        stub_status;
    }
    
  2. 重启nginx服务

    [root@web01 nginx]# 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 nginx]# systemctl reload nginx 
    
  3. 配置DNS信息
    编辑Window的hosts文件:10.0.0.7 status

  4. 网站监控测试

    Active connections: 激活的连接数信息,阈值3500
    accepts: 接收的TCP连接数汇总
    handled: 处理的TCP连接数汇总
    requests: HTTP协议请求数量汇总
    Reading: nginx服务读取请求报文的数量
    Writing: nginx服务响应报文信息数量
    Waiting: nginx队列机制,要处理(读取或者响应保存进行保存) 主要监控项

nginx日志功能配置

错误日志

错误日志:/var/log/nginx/error.log——Core functionality
Error_log官方文档
Error_log使用说明

Syntax:	error_log file [level];
Default:	
error_log logs/error.log error;
Context:	main, http, mail, stream, server, location

在/etc/nginx/nginx.conf中指定错误级别和路径信息

[root@web01 ~]# cat /etc/nginx/nginx.conf
user  www;
worker_processes  auto;
error_log  /var/log/nginx/error.log notice;    # 指定错误级别以及默认路径

错误级别

  • debug:调试级别, 服务运行的状态信息和错误信息详细显示
  • info:信息级别, 只显示重要的运行信息和错误信息
  • notice:通知级别, 更加重要的信息进行通知说明
  • warn:警告级别,可能出现了一些错误信息,但不影响服务运行
  • error:错误级别,服务运行已经出现了错误,需要进行纠正
  • crit:严重级别,必须进行修改调整
  • alert:严重警告级别,即警告且必须进行错误修改
  • emerg:灾难级别,服务已经不能正常运行

访问日志

访问日志:/var/log/nginx/access.log——ngx_http_log_module
ngx_http_log_module官方文档
ngx_http_log_module应用举例

log_format compression '$remote_addr - $remote_user [$time_local] '
                       '"$request" $status $bytes_sent '
                       '"$http_referer" "$http_user_agent" "$gzip_ratio"';

access_log /spool/logs/nginx-access.log compression buffer=32k;

ngx_http_log_module使用说明

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

在/etc/nginx/nginx.conf中指定访问日志格式和日志路径信息

    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;

查看/var/log/nginx/access.log日志内容

tail -1 /var/log/nginx/access.log

10.0.0.1 - - [06/Aug/2021:15:32:03 +0800] "GET /favicon.ico HTTP/1.1" 200 100 "http://status/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36" "-"
  • $remote_addr : 显示用户访问源IP地址信息
  • $remote_user : 显示认证的用户名信息
  • [$time_local] : 显示访问网站时间
  • “$request” : 请求报文的请求行信息
  • $status : 用户访问网站状态码信息
  • $body_bytes_sent : 显示响应的数据尺寸信息
  • $http_referer : 记录调用网站资源的连接地址信息
  • $http_user_agent : 记录用户访问页面的客户端软件
  • $http_x_forwarded_for : 负载均衡使用

自定义网站访问日志

  1. 编写配置文件
    [root@web01 ~]# vim /etc/nginx/conf.d/www.conf
    
    server {
        listen      80;
        server_name www.hello;
    
        access_log /var/log/nginx/www-access.log main;    # 定义网站访问日志
    
        location / {
            root /usr/share/nginx/html/www;
            # index index.html;
            auth_basic      "User authentication";
            auth_basic_user_file ./password/htpasswd;
            autoindex on;
            charset utf-8;
        }
    }
    
  2. 重启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 reload nginx.service 
    
  3. 测试访问网站
    [root@web01 ~]# curl www.hello -u letty:redhat
    <html>
    <head><title>Index of /</title></head>
    <body>
    ......
    
  4. 查看www-access.log日志文件
    [root@web01 ~]# tail /var/log/nginx/www-access.log 
    10.0.0.7 - letty [06/Aug/2021:15:59:07 +0800] "GET / HTTP/1.1" 200 838 "-" "curl/7.29.0" "-"
    

nginx服务location作用

location的作用是根据用户请求的URI来执行不同的应用,即根据用户请求的网站地址URL进行匹配,匹配成功即执行相关操作。

模块:ngx_http_core_module  location官方文档

网站优雅显示

  1. 编辑配置文件

    server {
        listen      80;
        server_name www.hello;
        location / {
            root /usr/share/nginx/html/www;
            error_page 404 /test.png;    # 当访问界面出现404时,显示站点目录下的test.png图片
        }
    }
    
  2. 重启nginx服务

    [root@web01 www]# 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 www]# systemctl reload nginx
    
  3. 测试404效果
    由于站点目录下没有access文件,因此自动跳转到test.png文件

网站服务匹配

location详细配置

语法:

Syntax:	location [ = | ~ | ~* | ^~ ] uri { ... }

该uri可以是普通的字符串地址路径,也可以是正则表达式,正则表达式前面还可以有~等特殊字符,匹配成功则执行后面大括号里的相关指令。

  • =:精确匹配
  • ~:区分大小写的正则匹配
  • ~*:不区分大小写的正则匹配
  • ^~:进行常规字符串匹配检查后,不做正则表达式的检查

匹配优先级:

  • 第一优先级:精确匹配(=)的优先级最高。一旦匹配成功,则不再查找其他匹配项。
  • 第二优先级:不匹配正则次之(^~)。一旦匹配成功,则不再查找其他匹配项。
  • 第三优先级:正则表达式类型(~ / ~*)的优先级次之。如果有多个location的正则能匹配的话,最长匹配原则。
  • 第四优先级:常规字符串匹配类型,按前缀匹配。

应用举例:

location = / {    # 精确匹配 
    [ configuration A ]
}

location / {    # 默认匹配 
    [ configuration B ]
}

location /documents/ {    # 目录匹配
    [ configuration C ]
}

location ^~ /images/ {    # 优先匹配/不进行正则匹配 
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {    # 不区分大小写匹配 优先级03
    [ configuration E ]
}

location匹配实战

  1. 编辑配置文件www.conf

    server {
        listen      80; 
        server_name www.hello;
        root /usr/share/nginx/html/www;
      
        location / { 
            return 401;
        }   
        location = / { 
            return 402;
        }   
        location /images/ {
            return 403;
        }   
        location ^~ /insert/ {
            return 404;
        }   
        location ~* \.(jpg|png)$ {
            return 500;
        }   
    }
    
  2. 重启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 reload nginx
    
  3. 访问测试

    [root@web01 ~]# curl -s -o /dev/null -I -w "%{http_code}\n" www.hello/index.html
    401
    [root@web01 ~]# curl -s -o /dev/null -I -w "%{http_code}\n" www.hello/not_exist
    401
    /index.html或任意不匹配其他location的字符串,即匹配了 location /,表示默认匹配,返回401
    
    [root@web01 ~]# curl -s -o /dev/null -I -w "%{http_code}\n" www.hello
    402
    [root@web01 ~]# curl -s -o /dev/null -I -w "%{http_code}\n" www.hello/
    402
    精确匹配,当为空或/时,匹配location = / ,返回402 
    
    [root@web01 ~]# curl -s -o /dev/null -I -w "%{http_code}\n" www.hello/insert/test.jpg
    404
    /insert/test.jpg ,匹配location ^~ /insert/,由于前面有特殊字符^~,匹配常规字符串,不做正则匹配,因此没有匹配结尾的test.jpg
    [root@web01 ~]# curl -s -o /dev/null -I -w "%{http_code}\n" www.hello/images/no_exist
    403
    /images/no_exist, 匹配location /images/, 目录匹配,匹配目录/images/
    [root@web01 ~]# curl -s -o /dev/null -I -w "%{http_code}\n" www.hello/images/test.jpg
    500
    test.jpg 正则匹配 location ~* \.(jpg|png)$ ,返回500
    

nginx实现页面跳转功能

Nginx rewrite的主要功能实现URL地址重写,Nginx的rewrite规则需要PCRE软件的支持,即通过Perl兼容正则表达式语法进行规则匹配。

模块

ngx_http_rewrite_module官方文档
ngx_http_rewrite_module使用语法

Syntax:	rewrite regex replacement [flag];   
      # rewite  匹配的正则信息  替换成什么信息
Default:	—
Context:	server, location, if

regex常用正则表达式字符

flag标记说明

  • last和breal实现URL重写时,浏览器地址栏的URL地址不变,在服务器端访问的程序及路径发生变化;

  • redirect和permanent实现URL重写时,浏览器地址栏会显示跳转后的URL地址。

  • 永久跳转:permanent 301 客户端会将跳转信息进行缓存,再次访问时直接在客户端跳转

  • 临时跳转:redirect 302 客户端不会缓存跳转信息,再次访问时还是在服务端进行跳转

实践

需求:实现访问www.hello跳转到bbs.hello

  1. 编辑www.hello配置文件

    server {
        listen      80;
        server_name www.hello hello;
        location / {
            root /usr/share/nginx/html/www;
            index index.html index.htm;
        }
        rewrite ^(.*) http://bbs.hello;
    }
    

    bbs.hello配置文件

    server {
        listen      80;
        server_name bbs.hello;
        location / {
            root /usr/share/nginx/html/bbs;
            index index.html;
        }
    }
    
  2. 重启nginx服务

    [root@web01 ~]# systemctl reload nginx.service
    
  3. 测试

    [root@web01 ~]# curl www.hello
    <html>
    <head><title>302 Found</title></head>
    <body>
    <center><h1>302 Found</h1></center>
    <hr><center>nginx/1.20.1</center>
    </body>
    </html>
    

更多推荐

Nginx网站服务

本文发布于:2023-04-17 20:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/4b5222bc7215c3c75bc103cf52d76a3b.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:网站   Nginx

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 84007文章数
  • 10883阅读数
  • 0评论数