nginx


nginx简介

nginx(发音同engine x)是一款轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like协议下发行。

nginx由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler使用。

第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。

nginx的特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

nginx的模块与工作原理

nginx的模块分类

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

  • HTTP模块、EVENT模块和MAIL模块等属于核心模块
  • HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块属于基本模块
  • HTTP Upstream模块、Request Hash模块、Notice模块和HTTP Access Key模块属于第三方模块

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

nginx模块从功能上分为三类,分别是:

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

nginx模块分为:核心模块、事件模块、标准Http模块、可选Http模块、邮件模块、第三方模块和补丁等

  • nginx基本模块:所谓基本模块,指的是nginx默认的功能模块,它们提供的指令,允许你使用定义nginx基本功能的变量,在编译时不能被禁用,包括:
    • 核心模块:基本功能和指令,如进程管理和安全。常见的核心模块指令,大部分是放置在配置文件的顶部
    • 事件模块:在Nginx内配置网络使用的能力。常见的events(事件)模块指令,大部分是放置在配置文件的顶部
    • 配置模块:提供包含机制

nginx的工作原理

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

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

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

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

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

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

nginx的安装与配置

nginx的安装

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

//安装依赖环境
[root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ make wget

//关闭防火墙和selinux
[root@localhost ~]# setenforce 0
[root@localhost ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@localhost ~]# systemctl disable --now firewalld.service

//创建日志存放目录
[root@localhost ~]# mkdir -p /var/log/nginx
[root@localhost ~]# chown -R nginx.nginx /var/log/nginx

//下载nginx源码包,并解压安装
[root@localhost ~]# wget http://nginx.org/download/nginx-1.20.2.tar.gz
[root@localhost ~]# tar xf nginx-1.20.2.tar.gz 
[root@localhost ~]# cd nginx-1.20.2
[root@localhost nginx-1.20.2]# ./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@localhost nginx-1.20.2]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install

//安装成功
[root@localhost nginx-1.20.2]# cd /usr/local/nginx/
[root@localhost nginx]# ls
conf  html  logs  sbin

nginx安装后配置

//配置环境变量
[root@localhost ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@localhost ~]# source /etc/profile.d/nginx.sh 
[root@localhost ~]# which nginx
/usr/local/nginx/sbin/nginx

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

//启动nginx
[root@localhost ~]# nginx
[root@localhost ~]# ss -anlt
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                [::]:22               [::]:*     

//关闭服务
[root@localhost ~]# nginx -s stop
[root@localhost ~]# ss -anlt
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               [::]:*       

//编写service文件
[root@localhost ~]# vi /usr/lib/systemd/system/nginx.service
[root@localhost ~]# cat /usr/lib/systemd/system/nginx.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

[Install]
WantedBy=multi-user.target


[root@localhost ~]# systemctl daemon-reload 
[root@localhost ~]# systemctl enable --now nginx.service 
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@localhost ~]# ss -anlt
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:*       

进行访问

平滑升级

平滑升级流程

  1. 获取老版本的编译信息
  2. 获取新版本安装包或者功能包
  3. 配置新版本或功能,配置时加上老版本的编译信息和新版本或功能
  4. 编译,编译后不执行安装操作
  5. 备份老版本程序
  6. 停止老版本程序或进程
  7. 将新版本复制到老版本所在位置替换老版本
  8. 启动新版本
//首先获取老版本编译信息
[root@nginx ~]# nginx -V
nginx version: nginx/1.20.2
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (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@nginx ~]# dnf -y install git
[root@nginx ~]# cd /usr/local/src/
[root@nginx src]# wget https://nginx.org/download/nginx-1.22.0.tar.gz
[root@nginx src]# git clone https://gitee.com/wujunze/nginx_module_echo.git
Cloning into 'nginx_module_echo'...
remote: Enumerating objects: 80, done.
remote: Total 80 (delta 0), reused 0 (delta 0), pack-reused 80
Unpacking objects: 100% (80/80), 14.32 KiB | 733.00 KiB/s, done.
[root@nginx src]# ls
nginx-1.22.0.tar.gz  nginx_module_echo
[root@nginx src]# tar xf nginx-1.22.0.tar.gz 
[root@nginx src]# ls
nginx-1.22.0  nginx-1.22.0.tar.gz  nginx_module_echo

//配置时,老版本的配置加上新加的模块,用--add-module=模块目录参数
[root@nginx src]# cd nginx-1.22.0
[root@nginx nginx-1.22.0]# ./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 \
> --add-module=../nginx_module_echo

//开始编译,别安装
[root@nginx nginx-1.22.0]# make -j $(grep 'processor' /proc/cpuinfo | wc -l)

//编译后的版本查看
[root@nginx nginx-1.22.0]# objs/nginx -v
nginx version: nginx/1.22.0

//替换版本,一条命令解决
[root@nginx nginx-1.22.0]# \cp /usr/local/nginx/sbin/nginx{,-bak};pkill nginx;\cp objs/nginx /usr/local/nginx/sbin/;systemctl start nginx

[root@nginx nginx-1.22.0]# nginx -v
nginx version: nginx/1.22.0
[root@nginx nginx-1.22.0]# ss -anlt
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                [::]:22               [::]:*   

nginx的配置文件

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

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

nginx常见的配置文件及其作用

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

nginx.conf配置详解

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

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

配置指令:要以分号结尾,语法格式如下:

derective value1 [value2 ...];

支持使用变量:

  • 内置变量:模块会提供内建变量定义
  • 自定义变量:set var_name value

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

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进程的用户和组
pid /path/to/pid_file;    //指定nginx守护进程的pid文件
worker_rlimit_nofile number;    //设置所有worker进程最大可以打开的文件数,默认为1024
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值

事件相关的配置: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的相关配置参数

LNMP:php要启用fpm模型
配置示例如下:

location ~ \.php$ {
  root html;
  fastcgi_pass 127.0.0.1:9000;      //定义反向代理
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  include fastcgi_params;
}

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时,匹配顺序如下:

  1. 先做精确匹配检查
  2. 左侧通配符匹配检查,如*.idfsoft.com
  3. 右侧通配符匹配检查,如mail.*
  4. 正则表达式匹配检查,如~ ^.*.idfsoft.com$
  5. 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各模块内建变量

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

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

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

常用修饰符说明:

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

~:表示指定的正则表达式要区分大小写,如:

server {
  server_name www.idfsoft.com;
  location ~ ^/abc$ {
  ......
  }
}

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

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

优先级次序如下:

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

展示效果:

//首先修改配置文件,这里匹配的有=修饰符,^~修饰符,无修饰符
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
    server {
        listen       80;
        server_name  localhost;
        
        location / {		//模糊匹配"/"开头的URI,这个优先级最低,当其他的都匹配不到时,匹配这个
            echo  "/";
        }
        location = /abc {	//精确匹配URI为"/abc"
            echo "= abc";
        }
        location ^~ /abc {	//匹配以"/abc"开头的URI,优先级低于修饰符"="
            echo "^abc";
        }
        location ~ ^/a {	//使用正则表达式匹配以"a"开头的URI,优先级低于修饰符"^~"
            echo "^/a";
        }

[root@nginx ~]# nginx -s reload 

//进行测试
##1.这次访问的的是"/abc",它的URI就是"/abc",被"location = /abc"精确匹配到,所以说修饰符"="优先级最高,打印了"=abc"
[root@nginx ~]# curl http://192.168.26.10/abc
= abc

##注意"?"后面部分不属于URI,所以说还能被"location = /abc",精确匹配到
[root@nginx ~]# curl http://192.168.26.10/abc?aa
= abc

##2.访问这个的URI是"/abc/",所以说不能被"location = /abc"精确匹配到,但是这个URI是以"/abc"开头的,所以说被"location ^~ /abc"优先匹配到
[root@nginx ~]# curl http://192.168.26.10/abc/
^abc
[root@nginx ~]# curl http://192.168.26.10/abc/abc
^abc
[root@nginx ~]# curl http://192.168.26.10/abcd/a
^abc
[root@nginx ~]# curl http://192.168.26.10/abcdef
^abc

##3.只要不被前两条匹配到,且以"a"开头的URI,就都会被"location ~ ^/a"匹配到
[root@nginx ~]# curl http://192.168.26.10/a
^/a
[root@nginx ~]# curl http://192.168.26.10/ab
^/a
[root@nginx ~]# curl http://192.168.26.10/a/a?
^/a

##4.只要上面的条件都不被匹配到"/",符合条件的只有"location /"这一条
[root@nginx ~]# curl http://192.168.26.10
/
[root@nginx ~]# curl http://192.168.26.10/
/
[root@nginx ~]# curl http://192.168.26.10/z
/

访问控制

用于location段
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开
示例:

//设置虚拟机不能访问
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
location / {
            root   html;
            index  index.html index.htm index.php;
            deny 192.168.26.10;      //添加这行
        }

[root@nginx ~]# systemctl restart nginx
[root@nginx ~]# curl http://192.168.26.10
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.22.0</center>
</body>
</html>

基于用户认证

对应系统资源的访问,我们往往需要限制谁能访问,谁不能访问。这块就是我们通常所说的认证部分,认证需要做的就是根据用户输入的用户名和密码来判定用户是否为合法用户,如果是则放行访问,如果不是则拒绝访问。

Nginx对应用户认证这块是通过ngx_http_auth_basic_module模块来实现的,它允许通过使用"HTTP基本身份验证"协议验证用户名和密码来限制对资源的访问。默认情况下nginx是已经安装了该模块,如果不需要则使用--without-http_auth_basic_module。

[root@nginx conf]# dnf -y install httpd-tools
[root@nginx conf]# htpasswd -bcm /usr/local/nginx/conf/htpasswd zdz 123456
Adding password for user zdz
[root@nginx conf]# ls
fastcgi.conf            htpasswd    mime.types.default  scgi_params.default
fastcgi.conf.default    koi-utf     nginx.conf          uwsgi_params
fastcgi_params          koi-win     nginx.conf.default  uwsgi_params.default
fastcgi_params.default  mime.types  scgi_params         win-utf
[root@nginx conf]# cat htpasswd 
zdz:$apr1$WoTAxxeJ$hhYk9sExwi1EhoqNlYmWK.

[root@nginx conf]# vim /usr/local/nginx/conf/nginx.conf
    server {
        listen       8080;
        server_name  localhost;
        location / {
             auth_basic           "closed site";
            auth_basic_user_file /usr/local/nginx/conf/htpasswd;
            root html;
            index  index.html index.htm;
        }
    }


https配置

开启状态界面

//禁止本虚拟机访问,默认其他都能访问
[root@nginx conf]# vim /usr/local/nginx/conf/nginx.conf
    server {
        listen       80;
        server_name localhost;

        location /status {
            stub_status on;
            deny 192.168.26.10;
        }
//虚拟机访问报错
[root@nginx conf]# curl http://192.168.26.10/status
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.22.0</center>
</body>
</html>

真实机访问成功

状态页面信息详解:

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

rewrite

语法:rewrite regex replacement flag;,如:

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

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

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

常见的flag

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

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

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

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

示列一

[root@nginx ~]# cd /usr/local/nginx/html/
[root@nginx html]# ls
50x.html  images  index.html  index.php
[root@nginx html]# cat images/index.html 
hehe


如果我们将此目录做了修改,将images修改为imge,那么用户使用原有的访问方式就访问不到了,而我们又不可能去告诉用户新的访问链接,所以,我们可以用rewrite去匹配用户输入的链接将其修改为新的链接,这样用户就相当于用旧的链接去访问到了新的连接,而用户并不知情

[root@nginx html]# ls
50x.html  images  index.html  index.php
[root@nginx html]# mv images imge
[root@nginx html]# ls
50x.html  imge  index.html  index.php
[root@nginx html]# vim ../conf/nginx.conf
location /images {
            rewrite ^/images/(.*)$ /imge/$1 break;
        }
[root@nginx html]# systemctl restart nginx

此时,我们用之前的链接去进行访问

新用户就让他用我们新修改的链接访问

示列二

[root@nginx html]# ls
50x.html  imge  index.html  index.php
[root@nginx html]# cat imge/index.html 
hehe

正常访问

//当访问以images为开头的任何东西的URI时,重写URI为http://www.itwangqing.net.cn/index.html
[root@nginx html]# vim ../conf/nginx.conf
        location /images {
            rewrite ^/images/(.*)$ http://www.itwangqing.net.cn/index.html break;
        }
[root@nginx html]# systemctl restart nginx

我们输入的是原链接,但是回车进行访问后,URL被重写成了http://www.itwangqing.net.cn/index.html

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;
  }
}
posted @   世界的尽头*  阅读(89)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示