nginx

nginx 的网站如果用源码安装的,是在安装目录的 html 里面

httpd 用源码安装是在安装目录里面的 htdocs 里面

nginx 的网站如果是 yum 安装的就在 /usr/share/nginx/html 里面

httpd yum安装则是在 /var/www/html 里面

1、Nginx介绍

nginx(发音同engine x)是一款轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like协议下发行。Nginx是由伊戈尔•赛索耶夫为俄罗斯访问量第二的Rambler.ru站点(俄文:Рамблер)开发的,第一个公开版本0.1.0发布于2004年10月4日。
其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。在全球活跃的网站中有12.18%的使用比率,大约为22200万个网站。
Nginx是一个安装非常简单、配置文件非常简洁(还能够支持perl语法),Bug非常少的服务,Nginx启动特别容易,并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动,你还能够不间断服务的情况下进行软件版本的升级。
Nginx代码完全用C语言从头写成,已经移植到许多体系结构和操作系统,包括:Linux、FreeBSD、Solaris、Mac OS X、AIX以及Microsoft Windows。官方数据表明能够支持高达 50,000 个并发连接数的响应,而我们常用的Tomcat一般500-600左右。

正向代理和反向代理可以理解为,一个是隐藏的用户,一个是隐藏的服务器。


2、Nginx的特性和优点




Nginx的特性

nginx是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性:

  • 在高连接并发的情况下,nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应
  • 使用epoll and kqueue作为开发模型
  • nginx作为负载均衡服务器:nginx既可在内部直接支持和PHP程序对外进行服务,也可支持作为HTTP代理服务器对外进行服务
  • nginx采用C进行编写,不论系统资源开销还是CPU使用效率都比Perlbal要好很多

Nginx的优缺点

优点:

  • 占内存小,可实现高并发连接(同时最多能接受多少来自用户的请求信息),处理响应快
  • 可实现http服务器、虚拟主机、方向代理、负载均衡
  • Nginx配置简单
  • 可以不暴露正式的服务器IP地址
    缺点:
  • 动态处理差:nginx处理静态文件好,耗费内存少,但是处理动态页面则很鸡肋,现在一般前端用nginx作为反向代理抗住压力

3、Nginx的功能及应用类别




Nginx的基本功能

  • 静态资源的web服务器,能缓存打开的文件描述符
  • http、smtp、pop3协议的反向代理服务器
  • 缓存加速、负载均衡
  • 支持FastCGI(fpm,LNMP),uWSGI(Python)等
  • 模块化(非DSO机制),过滤器zip、SSI及图像的大小调整
  • 支持SSL

Nginx的扩展功能

  • 基于名称和IP的虚拟主机
  • 支持keepalive
  • 支持平滑升级(用户感知不到升级)
  • 定制访问日志、支持使用日志缓冲区提高日志存储性能
  • 支持URL重写
  • 支持路径别名
  • 支持基于IP及用户的访问控制
  • 支持速率限制,支持并发数限制

Nginx应用场景

  • http服务器。Nginx是一个http服务可以独立提供http服务。可以做网页静态服务器。
  • 虚拟主机。可以实现在一台服务器虚拟出多个网站,例如个人网站使用的虚拟机
  • 反向代理,负载均衡。当网站的访问量达到一定程度后,单台服务器不能满足用户的请求时,需要用多台服务器集群可以使用nginx做反向代理。并且多台服务器可以平均分担负载,不会应为某台服务器负载高宕机而某台服务器闲置的情况。
  • nginz 中也可以配置安全管理、比如可以使用Nginx搭建API接口网关,对每个接口服务进行拦截。

4、Nginx的模块与工作原理
Nginx模块分类

Nginx的模块从结构上分为核心模块、基础模块和第三方模块:

  • 核心模块:HTTP模块、EVENT模块和MAIL模块。
  • 基础模块:HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块。
  • 第三方模块:HTTP Upstream Request Hash模块、Notice模块和HTTP Access Key模块。

用户根据自己的需要开发的模块都属于第三方模块。正是有了如此多模块的支撑,nginx的功能才会如此强大
Nginx的模块从功能上分为如下三类:

  • Proxies (代理类模块)。此类模块是Nginx的HTTP Upstream之类的模块,这些模块主要与后端一些服务比如FastCGI等进行交互,实现服务代理和负载均衡等功能。
  • Handlers(处理器模块)。此类模块直接处理请求,并进行输出内容和修改headers信息等操作。Handlers处理器模块一般只能有一个。
  • Filters (过滤器模块)。此类模块主要对其他处理器模块输出的内容进行修改操作,最后由Nginx输出。

Nginx的工作原理

nginx的模块直接被编译进nginx,因此属于静态编译方式。

启动nginx后,nginx的模块被自动加载,与Apache不一样,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。

在解析配置文件时,nginx的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。

nginx的进程架构:
启动nginx时,会启动一个Master进程,这个进程不处理任何客户端的请求,主要用来产生worker线程,一个worker线程用来处理n个request。

 下图展示了nginx模块一次常规的HTTP请求和响应的过程

 下图展示了基本的WEB服务请求步骤

5、Nginx的安装与配置




Nginx安装

//创建系统用户nginx
[root@nginx ~]# useradd -r -M -s /sbin/nologin nginx

//安装依赖环境
[root@nginx ~]#  yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++
[root@nginx ~]# yum -y groups mark install 'Development Tools'

//创建日志存放目录
[root@nginx ~]#  mkdir -p /var/log/nginx
[root@nginx ~]# chown -R nginx.nginx /var/log/nginx
[root@nginx ~]# cd /usr/src/
[root@nginx src]# wget http://nginx.org/download/nginx-1.12.1.tar.gz
--2021-10-25 22:24:23--  http://nginx.org/download/nginx-1.12.1.tar.gz
正在解析主机 nginx.org (nginx.org)... 3.125.197.172, 52.58.199.22, 2a05:d014:edb:5702::6, ...
正在连接 nginx.org (nginx.org)|3.125.197.172|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:980831 (958K) [application/octet-stream]
正在保存至: “nginx-1.12.1.tar.gz”

100%[============================================================>] 980,831      218KB/s 用时 4.4s   

2021-10-25 22:25:28 (218 KB/s) - 已保存 “nginx-1.12.1.tar.gz” [980831/980831])

[root@nginx src]# ls
debug  kernels  nginx-1.12.1.tar.gz
[root@nginx src]# tar xf nginx-1.12.1.tar.gz
[root@nginx src]# cd nginx-1.12.1
[root@nginx nginx-1.12.1]#  ./configure \
> --prefix=/usr/local/nginx \
> --user=nginx \
> --group=nginx \
> --with-debug \
> --with-http_ssl_module \
> --with-http_realip_module \
> --with-http_image_filter_module \
> --with-http_gunzip_module \
> --with-http_gzip_static_module \
> --with-http_stub_status_module \
> --http-log-path=/var/log/nginx/access.log \
> --error-log-path=/var/log/nginx/error.log

//安装软件
[root@nginx nginx-1.12.1]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install

Nginx配置

添加环境变量,让系统可以找到Nginx

[root@nginx ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@nginx ~]#  . /etc/profile.d/nginx.sh   //刷新

服务控制方式,使用nginx命令
控制选项

-t  //检查配置文件语法
-v  //输出nginx的版本
-c  //指定配置文件的路径
-s  //发送服务控制信号,可选值有{stop|quit|reopen|reload}

-t 检查配置文件语法是否有误

[root@nginx ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

-v 输出nginx的版本,大V列出编译安装时都安装了什么软件

//小v查看系统版本
[root@nginx ~]# nginx -v
nginx version: nginx/1.12.1

//大V查看编译安装时都安装了什么软件
[root@nginx nginx-1.12.1]# nginx -V
nginx version: nginx/1.12.1
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=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log
//-c 指定配置文件的路径
//以下操作修改配置文件并丝滑的让新的配置文件生效
[root@nginx ~]# cd /usr/local/nginx/conf/
[root@nginx conf]# ls
fastcgi.conf          fastcgi_params.default  mime.types          nginx.conf.default   uwsgi_params
fastcgi.conf.default  koi-utf                 mime.types.default  scgi_params          uwsgi_params.default
fastcgi_params        koi-win                 nginx.conf          scgi_params.default  win-utf
[root@nginx conf]# cp nginx.conf mime.types /opt/ #nginx.conf是配置文件,包含mime.types,所以这两个文件都需要一起copy过去
[root@nginx ~]# cd /opt/
[root@nginx opt]# ls
mime.types  nginx.conf
[root@nginx opt]# vi nginx.conf 
#user  nobody;
worker_processes  3; #修改数值
[root@nginx opt]# ps -ef|grep nginx
root        2443       1  0 19:09 ?        00:00:00 nginx: master process nginx
nginx       2444    2443  0 19:09 ?        00:00:00 nginx: worker process
root       18779   10152  0 19:16 pts/2    00:00:00 grep --color=auto nginx
[root@nginx opt]# nginx -s stop ; nginx -c /opt/nginx.conf #直接停掉然后启动
[root@nginx opt]# ps -ef|grep nginx
root       19164       1  0 19:16 ?        00:00:00 nginx: master process nginx -c /op
t/nginx.conf #发现worker变成修改的三个,新的配置文件生效
nginx      19165   19164  0 19:16 ?        00:00:00 nginx: worker process
nginx      19166   19164  0 19:16 ?        00:00:00 nginx: worker process
nginx      19167   19164  0 19:16 ?        00:00:00 nginx: worker process
root       19339   10152  0 19:16 pts/2    00:00:00 grep --color=auto nginx
//-s 发送服务控制信号,可选值有{stop|quit|reopen|reload}
[root@nginx opt]# nginx -s quit #非常优雅的停掉了它
[root@nginx opt]# ss -antl
State    Recv-Q   Send-Q       Local Address:Port       Peer Address:Port   Process   
LISTEN   0        128                0.0.0.0:22              0.0.0.0:*                
LISTEN   0        128                   [::]:22                 [::]:*   

开机自启

[root@nginx ~]# cp /usr/lib/systemd/system/sshd.service /usr/lib/systemd/system/nginxd.service
[root@nginx ~]# vim /usr/lib/systemd/system/nginxd.service
[Unit]
Description=nginx server daemon
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process

[Install]
WantedBy=multi-user.target

[root@nginx ~]# systemctl daemon-reload          //重新加载配置文件
[root@nginx ~]# systemctl enable --now nginxd    //启动nginx并设置开机自启
Created symlink /etc/systemd/system/multi-user.target.wants/nginxd.service → /usr/lib/systemd/system/nginxd.service.

6、nginx的配置文件详解

主配置文件:/usr/local/nginx/conf

默认启动nginx时,使用的配置文件是:安装路径/conf/nginx.conf文件
可以在启动nginx时通过-c选项来指定要读取的配置文件
nginx常见的配置文件及其作用

配置文件作用
nginx.confnginx的基本配置文件
mime.typesMIME类型关联的扩展文件
fastcgi.conf与fastcgi相关的配置
proxy.conf与proxy相关的配置
sites.conf配置nginx提供的网站,包括虚拟主机









nginx.conf配置详解

nginx.conf的内容分为以下几段:

main配置段:全局配置段。其中main配置段中可能包含event配置段
event {}:定义event模型工作特性
http {}:定义http协议相关的配置
Nginx配置文件示例

[root@localhost ~]# vim /usr/local/nginx/conf
# 全局块
 user www-data;  ##用户
 worker_processes  2;  ## 默认1,一般建议设成CPU核数1-2倍
 error_log  logs/error.log; ## 错误日志路径
 pid  logs/nginx.pid; ## 进程id
 # Events块
 events {
   # 使用epoll的I/O 模型处理轮询事件。
   # 可以不设置,nginx会根据操作系统选择合适的模型
   use epoll;
   # 工作进程的最大连接数量, 默认1024个
   worker_connections  2048;
   # http层面的keep-alive超时时间
   keepalive_timeout 60;
   # 客户端请求头部的缓冲区大小
   client_header_buffer_size 2k;
 }
 # http块
 http { 
   include mime.types;  # 导入文件扩展名与文件类型映射表
   default_type application/octet-stream;  # 默认文件类型
   # 日志格式及access日志路径
   log_format   main '$remote_addr - $remote_user [$time_local]  $status '
     '"$request" $body_bytes_sent "$http_referer" '
     '"$http_user_agent" "$http_x_forwarded_for"';
   access_log   logs/access.log  main; 
   # 允许sendfile方式传输文件,默认为off。
   sendfile     on;
   tcp_nopush   on; # sendfile开启时才开启。
 
   # http server块
   # 简单反向代理
   server {
     listen       80;
     server_name  domain2.com www.domain2.com;
     access_log   logs/domain2.access.log  main;
     # 转发动态请求到web应用服务器
     location / {
       proxy_pass      http://127.0.0.1:8000;
       deny 192.24.40.8;  # 拒绝的ip
       allow 192.24.40.6; # 允许的ip   
     }
     # 错误页面
     error_page   500 502 503 504  /50x.html;
         location = /50x.html {
             root   html;
         }
   }
   # 负载均衡
   upstream backend_server {
     server 192.168.0.1:8000 weight=5; # weight越高,权重越大
     server 192.168.0.2:8000 weight=1;
     server 192.168.0.3:8000;
     server 192.168.0.4:8001 backup; # 热备
   }
   server {
     listen          80;
     server_name     big.server.com;
     access_log      logs/big.server.access.log main;
     charset utf-8;
     client_max_body_size 10M; # 限制用户上传文件大小,默认1M
     location / {
       # 使用proxy_pass转发请求到通过upstream定义的一组应用服务器
       proxy_pass      http://backend_server;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header Host $http_host;
       proxy_redirect off;
       proxy_set_header X-Real-IP  $remote_addr;
     } 
   }
 }

用于调试、定位问题的配置参数

daemon {on|off};    //是否以守护进程方式运行nginx,调试时应设置为off
master_process {on|off};    //是否以master/worker模型来运行nginx,调试时可以设置为off
error_log 位置 级别;    //配置错误日志

error_log里的位置和级别能有以下可选项:

位置级别
file
stderr
syslog:server=address[,parameter=value]
memory:size
debug:若要使用debug级别,需要在编译nginx时使用--with-debug选项
info
notice
warn
error
crit
alert
emerg

 正常运行必备的配置参数

user USERNAME [GROUPNAME];    //指定运行worker进程的用户和组,用什么身份去运行worker进程
pid /path/to/pid_file;    //指定nginx守护进程的pid文件
worker_rlimit_nofile number;    //设置所有worker进程最大可以打开的文件数,默认为1024,最大设置为65535个,系统默认1024,所以nginx改了系统也得改
worker_rlimit_core size;    //指明所有worker进程所能够使用的总体的最大核心文件大小,保持默认即可

优化性能的配置参数


worker_processes n;    //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask ...;    //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:
    0000 0001   //第一颗cpu核心
    0000 0010   //第二颗cpu核心
    0000 0100   //第三颗cpu核心
    0000 1000   //第四颗cpu核心
    0001 0000   //第五颗cpu核心
    0010 0000   //第六颗cpu核心
    0100 0000   //第七颗cpu核心
    1000 0000   //第八颗cpu核心
timer_resolution interval;    //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数
worker_priority number;    //指明worker进程的nice值,优先级越高越好,值越小优先级越高,-20到19

事件相关的配置:event{}段中的配置参数

accept_mutex {off|on};    //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file;    //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll];    //指明使用的事件模型,建议让nginx自行选择
worker_connections #;    //每个进程能够接受的最大连接数

网络连接相关的配置参数

keepalive_timeout number;    //长连接的超时时长,默认为65s
keepalive_requests number;    //在一个长连接上所能够允许请求的最大资源数
keepalive_disable [msie6|safari|none];    //为指定类型的UserAgent禁用长连接
tcp_nodelay on|off;    //是否对长连接使用TCP_NODELAY选项,为了提升用户体验,通常设为on
client_header_timeout number;    //读取http请求报文首部的超时时长
client_body_timeout number;    //读取http请求报文body部分的超时时长
send_timeout number;    //发送响应报文的超时时长

fastcgi的相关配置参数

worker_processes 启动的worker进程几个
worker_connections 每个工作的进程处理的连接数
worker_cpu_affinity 工作进程倾向于在哪个cpu进程
worker_priority 每个进程优先级是多少

nginx作为web服务器时使用的配置:http{}段的配置参数

http{…}:配置http相关,由ngx_http_core_module模块引入。nginx的HTTP配置主要包括四个区块,结构如下:

http {//协议级别
  include mime.types;
  default_type application/octet-stream;
  keepalive_timeout 65;
  gzip on;
  upstream {//负载均衡配置
    ...
  }
  server {//服务器级别,每个server类似于httpd中的一个<VirtualHost>
    listen 80;
    server_name localhost;
    location / {//请求级别,类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系
      root html;
      index index.html index.htm;
    }
  }
}

http{}段配置指令:

server {}:定义一个虚拟主机,示例如下:

server {
  listen 80;
  server_name www.idfsoft.com;
  root "/vhosts/web";
}

listen:指定监听的地址和端口

listen address[:port];
listen port;

server_name NAME […]; 后面可跟多个主机,名称可使用正则表达式或通配符

当有多个server时,匹配顺序如下:

  • 先做精确匹配检查
  • 左侧通配符匹配检查,如*.idfsoft.com
  • 右侧通配符匹配检查,如mail.*
  • 正则表达式匹配检查,如~ ^.*.idfsoft.com$
  • default_server

root path; 设置资源路径映射,用于指明请求的URL所对应的资源所在的文件系统上的起始路径

alias path; 用于location配置段,定义路径别名

index file; 默认主页面

index index.php index.html;//谁优先谁在前面

error_page code […] [=code] URI | @name 根据http响应状态码来指明特用的错误页面,例如 error_page 404 /404_customed.html

[=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的响应码为其响应码,例如 error_page 404 =200 /404_customed.html

log_format 定义日志格式

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;

//注意:此处可用变量为nginx各模块内建变量

错误页面配置

//现在网页上下载一个公益网站传到html里
[root@localhost html]# ls
50x.html  中国社会公益网_files  中国社会公益网.html  index.html  index.php
[root@localhost html]# mv 中国社会公益网.html 404.html
[root@localhost html]# ls
404.html  50x.html  中国社会公益网_files  index.html  index.php
[root@localhost conf]# vim nginx.conf
  location / {
            root   html;
            index  index.php index.html index.htm;
        }

        error_page  404              /404.html; #取消注释

        # redirect server error pages to the static page /50x.html
        #
[root@localhost conf]# nginx -s stop;nginx 

 修改状态码为200

[root@localhost conf]# vim nginx.conf
  location / {
            root   html;
            index  index.php index.html index.htm;
        }

        error_page  404 = 200             /404.html; #取消注释

        # redirect server error pages to the static page /50x.html
        
[root@localhost conf]# nginx -s stop;nginx        #

  平滑升级

平滑升级:不能执行安装操作
1.获取老版本的编译参数 -V
2.获取新版本或新功能的软件包
3.对新功能或新版本的软件包进行编译
4.备份老版本
5.停掉老程序并用新程序使用老程序的配置文件进行启动
//获取新版本的软件包或功能包,下载地址 github.com
[root@localhost conf]# yum -y install unzip
[root@localhost src]# ls
debug                         mysql-5.7.34-linux-glibc2.12-x86_64.tar.gz
echo-nginx-module-master.zip  nginx-1.20.1.tar.gz
kernels                       php-8.0.10.tar.xz
[root@localhost src]# tar xf nginx-1.20.1.tar.gz 
[root@localhost src]# unzip echo-nginx-module-master.zip 

//获取现有的程序编译的参数
[root@localhost local]# nginx -V
nginx version: nginx/1.20.1
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-3) (GCC) 
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log

//将新功能或新版本进行编译
[root@localhost src]# cd nginx-1.20.1
[root@localhost nginx-1.20.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=../echo-nginx-module-master
[root@localhost nginx-1.20.1]# make

//备份原程序
[root@localhost nginx-1.20.1]# ll objs/nginx /usr/local/nginx/sbin/nginx
-rwxr-xr-x. 1 root root 6831056 10月 27 18:46 objs/nginx
-rwxr-xr-x. 1 root root 6308640 10月 26 18:39 /usr/local/nginx/sbin/nginx
[root@localhost nginx-1.20.1]# cp /usr/local/nginx/sbin/nginx /opt/
[root@localhost nginx-1.20.1]# ls /opt/
data  nginx

//停掉旧程序使用新程序,并测试
[root@localhost nginx-1.20.1]# nginx -s stop;objs/nginx -c /usr/local/nginx/conf/nginx.conf
[root@localhost conf]# vi nginx.conf
location /awm {
           echo 'my name is awm';  #添加
        }
        #error_page  404              /404.html;
[root@localhost nginx-1.20.1]# objs/nginx -s reload

//测试成功,覆盖旧程序
[root@localhost nginx-1.20.1]# \cp objs/nginx /usr/local/nginx/sbin/

//停掉新程序,去使用覆盖的程序
[root@localhost nginx-1.20.1]# objs/nginx -s stop;nginx 

location区段

location区段,通过指定模式来与客户端请求的URI相匹配

//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能

//语法:location [ 修饰符 ] pattern {......}

常用修饰符说明:

修饰符功能
=精确匹配
~正则表达式模式匹配,区分大小写
~*正则表达式模式匹配,不区分大小写
^~前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式
@定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等

示例

没有修饰符表示必须以指定模式开始

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
        location /test {              #匹配/test下的所有
             echo "test";
        }

        error_page  404           /404.html;

        # redirect server error pages to the static page /50x.html
[root@nginx ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx ~]# nginx -s reload

[root@nginx html]# curl  http://192.168.47.158
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
//那么如下内容就可正确匹配:
[root@localhost conf]# curl http://192.168.47.158/test
test
[root@localhost conf]# curl http://192.168.47.158/test/
test

=精确匹配

[root@localhost conf]# vim nginx.conf
       location /test {
        echo "test";
  }
        location = /test {
                echo "精确匹配"; #添加
        }
[root@localhost conf]# nginx -s reload
//可以匹配到
[root@localhost conf]# curl http://192.168.47.158/test
精确匹配

//一下内容匹配不到
[root@localhost conf]# curl http://192.168.47.158/test/
test
[root@localhost conf]# curl http://192.168.47.158/test/mmhh
test

查找顺序和优先级:由高到底依次为

  • 带有=的精确匹配优先
  • 正则表达式按照他们在配置文件中定义的顺序
  • 带有^~修饰符的,开头匹配
  • 带有~或 ~*修饰符的,如果正则表达式与URI匹配
  • 没有修饰符的精确匹配

优先级次序如下:

( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )

访问控制

[root@localhost conf]# vim nginx.conf
       location /test {
        root html;
        index index.html;   #添加
  }
        #error_page  404              /404.html;

[root@localhost test]# vim index.html
[root@localhost test]# cat index.html 
woshinidie
[root@localhost test]# pwd
/usr/local/nginx/html/test
[root@localhost conf]# nginx -s reload

[root@localhost conf]# vim nginx.conf
       location /test {
       #allow 192.168.47.1 #相当于白名单,设置白名单一般后面还会跟 deny all;才有意义
       deny 192.168.47.1; #相当于黑名单
        root html;
        index index.html;   
  }
        #error_page  404              /404.html;
[root@localhost conf]# nginx -s reload

用户认证 

[root@localhost conf]# vim nginx.conf
 location /test {
        auth_basic "穿过挪威的森林,让我走进你的梦里,夕阳落在我的铠甲,王子不一定骑着
白马,黑马王子四海为家,现在是晚上十点,我不是马思唯,也没有王子陪";
        auth_basic_user_file ".pass"; 
        root html;
        index index.html;
  }
        #error_page  404              /404.html;

[root@localhost conf]# yum -y install httpd-tools
//不是系统用户,是用来访问登录的用户
[root@localhost conf]# htpasswd -c -m .pass admin
New password: 
Re-type new password: 
Adding password for user admin
[root@localhost conf]# cat .pass 
admin:$apr1$0X8Bch7X$2WYa1obiFFB5.C9Yd8/fa0

 https


[root@localhost conf]# mkdir ssl
[root@localhost conf]# cd ssl
[root@localhost conf]# mkdir -p /etc/pki/CA
[root@localhost ssl]#  cd /etc/pki/CA
//生成密钥
[root@localhost CA]# mkdir private && (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
................................+++++
.................................................................................................+++++
e is 65537 (0x010001)
[root@localhost CA]# ls
private
//生成自签证书
[root@localhost CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:rumtime
Organizational Unit Name (eg, section) []:rumtime
Common Name (eg, your name or your server's hostname) []:test.runtime.com
Email Address []:1@2.com
[root@localhost CA]# mkdir certs newcerts crl
[root@localhost CA]# ls
cacert.pem  certs  crl  newcerts  private
[root@localhost CA]# touch index.txt && echo 01 > serial
[root@localhost CA]# ls
cacert.pem  certs  crl  index.txt  newcerts  private  serial

//生成密钥
[root@localhost ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
......+++++
....................................................+++++
e is 65537 (0x010001)
[root@localhost ssl]# ls
nginx.key
[root@localhost ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
Ignoring -days; not generating a certificate
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:rumtime
Organizational Unit Name (eg, section) []:rumtime
Common Name (eg, your name or your server's hostname) []:test.runtime.com
Email Address []:1@2.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@localhost ssl]# ll
总用量 8
-rw-r--r--. 1 root root 1033 10月 27 22:23 nginx.csr
-rw-------. 1 root root 1679 10月 27 22:20 nginx.key
[root@localhost ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Oct 27 14:26:54 2021 GMT
            Not After : Oct 27 14:26:54 2022 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = rumtime
            organizationalUnitName    = rumtime
            commonName                = test.runtime.com
            emailAddress              = 1@2.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                E4:31:1D:62:46:1B:33:0E:49:27:D8:2E:AC:93:7D:CF:4E:1C:53:D8
            X509v3 Authority Key Identifier: 
                keyid:3A:BE:A2:4E:93:D1:EA:11:7C:4B:F6:68:03:F8:67:33:D4:71:BB:44

Certificate is to be certified until Oct 27 14:26:54 2022 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@localhost ssl]# rm -rf nginx.csr 
[root@localhost ssl]# ls
nginx.crt  nginx.key
[root@localhost conf]# vim nginx.conf

server {     						#这些都取消注释
        listen       443 ssl;
        server_name  test.runtime.com;

        ssl_certificate      ssl/nginx.crt; #修改证书的位置
        ssl_certificate_key  ssl/nginx.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;
        }
    }
[root@localhost conf]# nginx -s reload
[root@localhost conf]# ss -antl
State    Recv-Q   Send-Q       Local Address:Port       Peer Address:Port   Process   
LISTEN   0        128                0.0.0.0:22              0.0.0.0:*                
LISTEN   0        128                0.0.0.0:443             0.0.0.0:*                
LISTEN   0        128                0.0.0.0:80              0.0.0.0:*                
LISTEN   0        128                   [::]:22                 [::]:*                

访问(输入主机ip即可)

开启状态界面

开启status:

location /status {
  stub_status {on | off};
  allow 172.16.0.0/16;
  deny all;
}

访问状态页面的方式:http://server_ip/status

状态页面信息详解:

状态码表示的意义
Active connections 2当前所有处于打开状态的连接数
accepts总共处理了多少个连接
handled成功创建多少握手
requests总共处理了多少个请求
Readingnginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数
Writingnginx返回给客户端的Header信息数,表示请求已经接收完成,且正处于处理请求或发送响应的过程中的连接数
Waiting开启keep-alive的情况下,这个值等于active - (reading + writing),意思就是Nginx已处理完正在等候下一次请求指令的驻留连接

状态页面配置与监控

开启状态页面功能

[root@localhost conf]# vim nginx.conf
    location /status {
        stub_status;
        allow 192.168.47.133;
  }
[root@localhost conf]# nginx -s reload

 一台zabbix_server主机IP为192.168.47.133
另一台zabbix_agent,nginx主机IP为192.168.47.158

[root@localhost zabbix-5.4.4]# tr -dc A-Za-z < /dev/urandom | head -c 8 |xargs
UjRLyABB
[root@localhost zabbix-5.4.4]# cd /usr/local/etc/
[root@localhost etc]# ls
zabbix_agentd.conf  zabbix_agentd.conf.d
[root@localhost etc]# vim zabbix_agentd.conf
# Default:
# Server=
Server=192.168.47.133 //修改为服务端server主机ip,被动模式
### Option: ListenPort
# ServerActive=
ServerActive=192.168.47.133 //修改为服务端主机ip,主动模式
### Option: Hostname
# Hostname=
Hostname=UjRLyABB //随机码,必须得全局唯一,可以是IP地址,也可以随机
### Option: HostnameItem

[root@localhost etc]# zabbix_agentd 
[root@localhost etc]# ss -antl
State    Recv-Q   Send-Q      Local Address:Port        Peer Address:Port   Process   
LISTEN   0        128               0.0.0.0:80               0.0.0.0:*                
LISTEN   0        128               0.0.0.0:22               0.0.0.0:*                
LISTEN   0        128               0.0.0.0:443              0.0.0.0:*                
LISTEN   0        128               0.0.0.0:10050            0.0.0.0:*                
LISTEN   0        128                  [::]:22                  [::]:*       

[root@localhost conf]# cat status.sh 
#!/bin/bash

if [ `curl -s http://192.168.47.158/status|awk 'NR==4 {print $4}' ` -ne 0 ];then
    echo 1
else
    echo 0
fi
[root@localhost conf]# chmod +x status.sh 

[root@localhost etc]# vim zabbix_agentd.conf
# Default:
UnsafeUserParameters=1
# ListenBacklog=
UserParameter=check_status[*],/usr/local/nginx/conf/status.sh
[root@localhost etc]# pkill zabbix_agentd
[root@localhost etc]# zabbix_agentd 
[root@133 ~]# zabbix_get -s 192.168.47.158 -k check_status
0

 

 

 

 

 

rewrite

语法:rewrite regex replacement flag;,如:

rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;

此处的$1用于引用(.*.jpg)匹配到的内容,又如:

rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

如上例所示,replacement可以是某个路径,也可以是某个URL

常见的flag

flag作用
last基本上都用这个flag,表示当前的匹配结束,继续下一个匹配,最多匹配10个到20个
一旦此rewrite规则重写完
成后,就不再被后面其它的rewrite规则进行处理
而是由UserAgent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程
break中止Rewrite,不再继续匹配
一旦此rewrite规则重写完成后,由UserAgent对新的URL重新发起请求,
且不再会被当前location内的任何rewrite规则所检查
redirect以临时重定向的HTTP状态302返回新的URL
permanent以永久重定向的HTTP状态301返回新的URL

rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)

nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:

标识符意义
^必须以^后的实体开头
$必须以$前的实体结尾
.匹配任意字符
[]匹配指定字符集内的任意字符
[^]匹配任何不包括在指定字符集内的任意字符串
竖杠匹配
()分组,组成一组用于匹配的实体,通常会有

实例:

break示例

[root@localhost html]# mkdir images
[root@localhost images]# ls
1.jpg
[root@localhost images]# pwd
/usr/local/nginx/html/images

访问

 将存放图片的文件夹images更改为imgs

[root@localhost html]# ls
50x.html  images  index.html  test
[root@localhost html]# mv images/ imgs
[root@localhost html]# ls
50x.html  imgs  index.html  test

 

[root@localhost conf]# vim nginx.conf
      location /images {
        rewrite ^/images/(.*\.jpg)$ /imgs/$1 break; # 添加//当匹配images时自动重定向到imgs
  }
        #error_page  404              /404.html;
[root@localhost conf]# nginx -s reload

再去访问images目录就会重定向到imgs目录

 break实例二

[root@localhost conf]# vim nginx.conf
       location /images {
        rewrite ^/images/(.*\.jpg)$ https://www.baidu.com/ break;
  }
[root@localhost conf]# nginx -s reload

last 向后匹配

[root@localhost conf]# vim nginx.conf
location /images {
                rewrite ^/images/(.*\.jpg)$ /imgs/$1 last; //当匹配到imgs时,因为有last,所以会继续向后匹配
        }
        location /imgs {
                rewrite ^/imgs/(.*)$ http://images.baidu.com last;  // 匹配到这里
        }
[root@localhost conf]# nginx -s reload

 last,break

[root@localhost conf]# vim nginx.conf
location /images {
                rewrite ^/images/(.*\.jpg)$ /imgs/$1 break; //中止
        }
        location /imgs {
                rewrite ^/imgs/(.*)$ http://images.baidu.com last;  
        }
[root@localhost conf]# nginx -s reload

 if

语法:if (condition) {…}

应用场景:

  • server段
  • location段
    常见的condition
    变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)
    以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
    正则表达式的模式匹配操作
    ~:区分大小写的模式匹配检查
    ~:不区分大小写的模式匹配检查
    !和!:对上面两种测试取反
    测试指定路径为文件的可能性(-f,!-f)
    测试指定路径为目录的可能性(-d,!-d)
    测试文件的存在性(-e,!-e)
    检查文件是否有执行权限(-x,!-x)

基于浏览器实现分离案例

if ($http_user_agent ~ Firefox) {
  rewrite ^(.*)$ /firefox/$1 break;
}

if ($http_user_agent ~ MSIE) {
  rewrite ^(.*)$ /msie/$1 break;
}

if ($http_user_agent ~ Chrome) {
  rewrite ^(.*)$ /chrome/$1 break;
}

防盗链案例

location ~* \.(jpg|gif|jpeg|png)$ {
  valid_referers none blocked www.idfsoft.com;
  if ($invalid_referer) {
    rewrite ^/ http://www.idfsoft.com/403.html;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值