nginx

web服务基础介绍

在这里插入图片描述

单次web服务访问流程:

首先在浏览器输入http://…(超文本传输协议),通过网络访问web服务器,web服务器分为两种资源,一种是能够通过对于磁盘的访问直接取到,然后构建响应报文再直接传递给客户,另一种为需要处理的比如php,php在处理时需要使用php语言对代码进行解析,解析完成后再将最后结果传递给web服务器,web服务器再产生响应报文发送给客户。

nginx的源码编译

以rhel9.3为例,关闭了防火墙和selinux

1.下载nginx包并解压

[root@nginx-node1 ~] tar zxf nginx-1.24.0.tar.gz
[root@nginx-node1 ~] cd nginx-1.24.0/
[root@nginx-node1 nginx-1.24.0] ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src #configure环境检测

2.安装相应的数据包

[root@nginx-node1 nginx-1.24.0] dnf install gcc pcre-devel zlib-devel openssl-devel -y

3.执行环境检测命令

[root@Nginx nginx-1.24.0] ./configure --prefix=/usr/local/nginx \ #安装到/usr/local/nginx  \:表示换行  检测后会自动生成响应文件
--user=nginx \ 							# 指定nginx运行用户
--group=nginx \ 						# 指定nginx运行组
--with-http_ssl_module \ 				# 支持https://
--with-http_v2_module \ 				# 支持http版本2
--with-http_realip_module \ 			# 支持ip透传
--with-http_stub_status_module \ 		# 支持状态页面
--with-http_gzip_static_module \ 		# 支持压缩
--with-pcre \ 							# 支持正则
--with-stream \ 						# 支持tcp反向代理
--with-stream_ssl_module \ 				# 支持tcp的ssl加密
--with-stream_realip_module 			# 支持tcp的透传ip
[root@nginx-node1 nginx-1.24.0] ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  Makefile  man  objs  README  src #Makefile:make执行规则
#若想还原之前检测操作
[root@nginx-node1 nginx-1.24.0] make clean
#会删除Makefile和 objs

4.开始编译

[root@nginx-node1 nginx-1.24.0] make && make install
#make:开始编译
#make install:将make生成的objs文件内容拷贝到指定的目录中

5.启动脚本

[root@nginx-node1 nginx-1.24.0] cd /usr/local/nginx/sbin/
[root@nginx-node1 sbin] ls
nginx
[root@nginx-node1 sbin] useradd -s /sbin/nologin -M nginx #创建nginx用户
[root@nginx-node1 sbin] ./nginx
[root@nginx-node1 sbin] ps aux | grep nginx  #默认生成一个主进行和一个工作进程
root        7643  0.0  0.0   9920   940 ?        Ss   21:44   0:00 nginx: master process ./nginx
nginx       7644  0.0  0.1  13760  4680 ?        S    21:44   0:00 nginx: worker process
root       16815  0.0  0.0   6408  2164 pts/0    S+   22:24   0:00 grep --color=auto nginx

6.效果展示

[C:\~]$ curl 172.25.254.100
<!DOCTYPE html>
               <html>
                     <head>
                           <title>Welcome to nginx!</title>
                                                           <style>
#能出现nginx的html界面

拓展:

减少nginx容量

#关闭nginx命令
[root@nginx-node1 ~] /usr/local/nginx/sbin/nginx -s stop
#重启nginx命令
[root@nginx-node1 ~] /usr/local/nginx/sbin/nginx -s restart
[root@nginx-node1 sbin] du -sh nginx 
5.4M	nginx #此时的nginx比较大,是因为开启了debug模式

1.删除nginx

[root@nginx-node1 ~] rm -rf /usr/local/nginx
[root@nginx-node1 nginx-1.24.0] make clean

2.关闭debug功能

[root@nginx-node1 nginx-1.24.0] vim auto/cc/gcc
# debug
#CFLAGS="$CFLAGS -g"

3.再次检测并生成文件

[root@nginx-node1 nginx-1.24.0]

4.再次编译

[root@nginx-node1 nginx-1.24.0] make && make install 

编写环境变量文件

[root@nginx-node1 nginx-1.24.0] vim ~/.bash_profile #当前用户家目录的环境变量文件
#执行的目的是为了把nginx软件的命令执行路径添加到环境变量中,可以直接执行
[root@nginx-node1 nginx-1.24.0] cat ~/.bash_profile 
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
	. ~/.bashrc
fi

# User specific environment and startup programs
export PATH=$PATH:/usr/local/nginx/sbin
[root@nginx-node1 nginx-1.24.0] source ~/.bash_profile 

5.效果展示

[root@nginx-node1 nginx-1.24.0] du -sh /usr/local/nginx/sbin/
1.2M	/usr/local/nginx/sbin/

nginx的平滑升级和版本回退

1.安装nginx1.26版本和添加模块

[root@nginx-node1 ~] tar zxf nginx-1.26.2.tar.gz 
[root@nginx-node1 ~] tar zxf echo-nginx-module-0.63.tar.gz 

2.进入1.26.2,并进行检测

[root@nginx-node1 nginx-1.26.2] ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --add-module=/root/echo-nginx-module-0.63 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
#在进行检测时顺便加入echo模块

修改nginx版本信息

[root@nginx-node1 core] vim /root/nginx-1.26.2/src/core/nginx.h
/*
 * Copyright (C) Igor Sysoev
 * Copyright (C) Nginx, Inc.
 */


#ifndef _NGINX_H_INCLUDED_
#define _NGINX_H_INCLUDED_


#define nginx_version      1026002
#define NGINX_VERSION      "1.0"
#define NGINX_VER          "jisoo/" NGINX_VERSION #可以自己修改

3.进行编译

[root@nginx-node1 nginx-1.26.2] make #注意,不能make install
#编译完成生成的资源会生成在objs中
[root@nginx-node1 nginx-1.26.2] ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  Makefile  man  objs  README  src
[root@nginx-node1 nginx-1.26.2] cd objs/
[root@nginx-node1 objs] ls
addon         Makefile  nginx.8            ngx_auto_headers.h  ngx_modules.o
autoconf.err  nginx     ngx_auto_config.h  ngx_modules.c       src

4.替换文件

[root@nginx-node1 objs] cd /usr/local/nginx/sbin/
[root@nginx-node1 sbin] ll
total 11580
-rwxr-xr-x. 1 root root 6176600 Aug 15 11:55 nginx 
-rwxr-xr-x. 1 root root 5678264 Aug 15 11:45 nginx.old
#在替换文件之前需要确保环境没有问题
[root@nginx-node1 sbin]  nginx -s stop
[root@nginx-node1 sbin] cd
[root@nginx-node1 ~] rm -rf /usr/local/nginx/
[root@nginx-node1 ~] cd /root/nginx-1.24.0/
[root@nginx-node1 ~] make install
[root@nginx-node1 nginx] cd /usr/local/nginx/sbin/
[root@nginx-node1 sbin] ls
nginx #只有一个文件,#此文件为1.24生成的nginx文件
[root@nginx-node1 sbin] cp nginx nginx.old #将以前的nginx文件备份
[root@nginx-node1 sbin]  ll
total 11096
-rwxr-xr-x 1 root root 5678256 Aug 15 23:10 nginx
-rwxr-xr-x 1 root root 5678256 Aug 15 23:12 nginx.old
[root@nginx-node1 sbin] \cp -f /root/nginx-1.26.2/objs/nginx /usr/local/nginx/sbin/ #将1.24文件替换为1.26文件
[root@nginx-node1 sbin] ll
total 11580
-rwxr-xr-x 1 root root 6176600 Aug 15 23:14 nginx
-rwxr-xr-x 1 root root 5678256 Aug 15 23:12 nginx.old

5.查看进程

[root@nginx-node1 sbin] nginx #启动nginx
[root@nginx-node1 sbin] ps aux | grep nginx
root        5369  0.0  0.0   9956   960 ?        Ss   23:18   0:00 nginx: master process nginx
nginx       5370  0.0  0.1  13812  4764 ?        S    23:18   0:00 nginx: worker process
root        5373  0.0  0.0   6408  2180 pts/0    S+   23:18   0:00 grep --color=auto nginx
[root@nginx-node1 sbin] kill -USR2 5369 #激活usr2进程
[root@nginx-node1 sbin] ps aux | grep nginx
root        5369  0.0  0.0   9956  2592 ?        Ss   23:18   0:00 nginx: master process nginx #1.24主进程
nginx       5370  0.0  0.1  13812  4764 ?        S    23:18   0:00 nginx: worker process #1.24工作进程
root        5374  0.0  0.1   9828  6484 ?        S    23:18   0:00 nginx: master process nginx #1.26主进程
nginx       5375  0.0  0.1  13800  4736 ?        S    23:18   0:00 nginx: worker process #1.26工作进程
root        5377  0.0  0.0   6408  2176 pts/0    S+   23:18   0:00 grep --color=auto nginx

6.回收进行

#通过回收旧进程实现版本更替
[root@nginx-node1 sbin] kill -WINCH 5369 #回收旧的工作进程
[root@nginx-node1 sbin] ps aux | grep nginx
root        5369  0.0  0.0   9956  2592 ?        Ss   23:18   0:00 nginx: master process nginx
root        5374  0.0  0.1   9828  6484 ?        S    23:18   0:00 nginx: master process nginx
nginx       5375  0.0  0.1  13800  4736 ?        S    23:18   0:00 nginx: worker process
[root@nginx-node1 sbin] curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.26.2 #替换成了1.26
Date: Thu, 15 Aug 2024 15:27:32 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Thu, 15 Aug 2024 15:10:00 GMT
Connection: keep-alive
ETag: "66be1a48-267"
Accept-Ranges: bytes
#通过激活进程实现版本回滚
[root@nginx-node1 ~]# cd /usr/local/nginx/sbin/
[root@nginx-node1 sbin]# ll
total 6836
-rwxr-xr-x. 1 root root 5752872 Aug 16 00:33 nginx
-rwxr-xr-x. 1 root root 1241208 Aug 16 00:30 nginx.24
[root@nginx-node1 sbin]# cp nginx nginx.26
[root@nginx-node1 sbin]# ll
total 12456
-rwxr-xr-x. 1 root root 5752872 Aug 16 00:33 nginx
-rwxr-xr-x. 1 root root 1241208 Aug 16 00:30 nginx.24
-rwxr-xr-x. 1 root root 5752872 Aug 16 00:43 nginx.26
[root@nginx-node1 sbin]# mv nginx.24 nginx
mv: overwrite 'nginx'? y

[root@nginx-node1 sbin] kill -HUP 5369 #激活1.24进程
[root@nginx-node1 sbin] ps aux | grep nginx
root        5369  0.0  0.0   9956  2592 ?        Ss   23:18   0:00 nginx: master process nginx
root        5374  0.0  0.1   9828  6484 ?        S    23:18   0:00 nginx: master process nginx
nginx       5375  0.0  0.1  13800  4736 ?        S    23:18   0:00 nginx: worker process
nginx       5383  0.0  0.1  13812  4768 ?        S    23:29   0:00 nginx: worker process #生成的1.24进程的工作进程
#再次回收1.26进程实现回退
[root@nginx-node1 sbin] kill -WINCH 5374
[root@nginx-node1 sbin] ps aux | grep nginx
root        5369  0.0  0.0   9956  2592 ?        Ss   23:18   0:00 nginx: master process nginx
root        5374  0.0  0.1   9828  6484 ?        S    23:18   0:00 nginx: master process nginx
nginx       5383  0.0  0.1  13812  4768 ?        S    23:29   0:00 nginx: worker process
root        5388  0.0  0.0   6408  2180 pts/0    S+   23:31   0:00 grep --color=auto nginx
[root@nginx-node1 sbin] curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Thu, 15 Aug 2024 15:45:40 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Thu, 15 Aug 2024 15:44:24 GMT
Connection: keep-alive
ETag: "66be2258-267"
Accept-Ranges: bytes

nginx常见基础命令

[root@nginx-node1 ~] nginx -V #查看nginx信息
nginx version: nginx/1.24.0 #版本
built by gcc 11.4.1 20230605 (Red Hat 11.4.1-2) (GCC) 
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module #编译过程中使用的参数

[root@nginx-node1 sbin] 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

nginx启动脚本编写

[root@nginx-node1 sbin] vim /lib/systemd/system/nginx.service #创建文件,建议名字与之前使用的名字一致
[Unit] #环境
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service] #启动服务的主题
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t #执行真实启动命令之前检测配置文件是否有误
ExecStart=/usr/local/nginx/sbin/nginx #真实启动命令
ExecReload=/usr/local/nginx/sbin/nginx -s reload #真实reload命令
ExecStop=/bin/kill -s QUIT $MAINPID #真实stop命令
PrivateTmp=true
[Install] #开机启动在哪个模式下做的
WantedBy=multi-user.target   
[root@nginx-node1 sbin] systemctl daemon-reload
[root@nginx-node1 sbin] nginx -s stop
[root@nginx-node1 sbin] systemctl enable --now nginx

nginx核心配置

Nginx的配置文件的组成部分:

  • 主配置文件:nginx.conf
  • 子配置文件: include conf.d/*.conf
  • fastcgi, uwsgi,scgi 等协议相关的配置文件
  • mime.types:支持的mime类型,MIME(Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型,MIME消息能包含文本、图像、音频、视频以及其他应用程序专用的数据,是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式。

nginx全局优化

[root@nginx-node1 sbin] vim /usr/local/nginx/conf/nginx.conf
user  nginx nginx; #nginx运行的用户
worker_processes  auto; #启动的工作数量
worker_cpu_affinity 01 10; #cpu核心绑定,双核写两个

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events { #应用的模块
    worker_connections  100000; #支持的最大并发连接数
    use epoll;
}


http {
    include       mime.types; #包含的文件最终资源类型
    default_type  application/octet-stream; #默认类型为
    sendfile      on;0拷贝
    
    #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;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65 60; #长连接保持时间为65s,给用户看到的时间为60s
    keepalive_requests 2;

    gzip  on;
........

增加设置nginx最大并发连接数

[root@nginx-node1 sbin] vim /etc/security/limits.conf
*               -       nofile          100000 #末尾添加
[root@nginx-node1 sbin]# sudo -u nginx ulimit -a
real-time non-blocking time  (microseconds, -R) unlimited
core file size              (blocks, -c) 0
data seg size               (kbytes, -d) unlimited
scheduling priority                 (-e) 0
file size                   (blocks, -f) unlimited
pending signals                     (-i) 6763
max locked memory           (kbytes, -l) 8192
max memory size             (kbytes, -m) unlimited
open files                          (-n) 100000
pipe size                (512 bytes, -p) 8
POSIX message queues         (bytes, -q) 819200
real-time priority                  (-r) 0
stack size                  (kbytes, -s) 8192
cpu time                   (seconds, -t) unlimited
max user processes                  (-u) 6763
virtual memory              (kbytes, -v) unlimited
file locks                          (-x) unlimited

安装压测工具

[root@nginx-node1 sbin] yum install httpd-tools -y
[root@nginx-node1 sbin] ab -n 100 -c 50 http://172.25.254.100/index.html
# -n:链接数量  -c:并发链接数

新建一个web站点

user  nginx nginx;
worker_processes  auto;
worker_cpu_affinity 01 10;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  100000;
    use epoll; #使用epoll模型 
}


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

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65 60;
    keepalive_requests 2;

    #gzip  on;
    include  "/usr/local/nginx/conf.d/*.conf" ;
    #注意一定要写在前面
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

[root@nginx-node1 nginx-1.24.0]# mkdir -p /usr/local/nginx/conf.d
[root@nginx-node1 ~] echo www.timinglee.org > /usr/local/nginx/conf.d/index.html
[root@nginx-node1 ~] nginx -s reload
[root@nginx-node1 ~] curl www.timinglee.org

nginx配置中的root和alias

#root
[root@nginx-node1 ~] vim /usr/local/nginx/conf.d/vhost.conf
server {
        listen 80;
        server_name www.timinglee.org;
        root /data/web/html;
        index index.html;

        location /test1 {
                root /data/web;
        }
}
[root@nginx-node1 ~] nginx -s reload
[root@nginx-node1 ~] mkdir /data/web/test1 -p
[root@nginx-node1 ~] echo /data/web/test1 > /data/web/test1/index.html

在这里插入图片描述

#alias
[root@nginx-node1 ~]# vim /usr/local/nginx/conf.d/vhost.conf 
server {
        listen 80;
        server_name www.timinglee.org;
        root /data/web/html;
        index index.html;

        location /test1 {
                root /data/web; #root,相当于追加
        }

        location /test2 {
                alias /data/web/test1; #alias,相当于替换
        }
}

[root@nginx-node1 ~]# nginx -s reload

在这里插入图片描述

nginx高级配置

nginx 状态页

  • 基于nginx 模块 ngx_http_stub_status_module 实现
  • 在编译安装nginx的时候需要添加编译参数 --with-http_stub_status_module
  • 否则配置完成之后监测会是提示法错误
[root@nginx-node1  ~]# cd /usr/local/nginx/conf.d/
[root@nginx-node1  conf.d]# vim vhost.conf 
[root@nginx-node1  conf.d]# vim status.conf
[root@nginx-node1 conf.d]# nginx -s relod
server {
    listen 80;
    server_name status.example.org;
    root /data/web/html;
    index index.html;
    location /status {
        stub_status;
        auth_basic "login";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
	}

}

Nginx 压缩功能

[root@nginx-node1 conf.d] vim /usr/local/nginx/conf/nginx.conf
	gzip  on;
    gzip_comp_level 5;
    gzip_min_length 1k;
    gzip_http_version 1.1;
    gzip_buffers number size;
    gzip_vary on;
	gzip_types text/plain application/javascript application/x-javascript text/css
application/xml text/javascript application/x-httpd-php image/gif image/png;
[root@nginx-node1 conf.d] nginx -s reload
[root@nginx-node1 conf.d] nginx -t
 
[root@nginx-node1 conf.d] echo hello example xixi > /data/web/html/small.html
[root@nginx-node1 conf.d] cat /var/log/example.org/access.log > /data/web/html/big.html
root@nginx-node1 conf.d] curl --head --compressed 172.25.254.100/small.html
[root@nginx conf.d] curl --head --compressed 172.25.254.100/big.html

nginx变量使用

nginx的变量可以在配置文件中引用,作为功能判断或者日志等场景使用
[root@nginx-node1 conf.d] nginx -V
nginx version: nginx/1.26.2
built by gcc 11.4.1 20230605 (Red Hat 11.4.1-2) (GCC) 
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --add-module=/root/echo-nginx-module-0.63 #此模块在之前加过,有此模块才能进行echo --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module

[root@nginx-node1 conf.d] vim /usr/local/nginx/conf.d/vars1.conf
server {
    listen 80;
    server_name var.timinglee.org;
    root /data/web/html;
    index index.html;

    location /var {
        default_type text/html;
        echo $remote_addr; #存放的远程ip
        echo $args; #url中的参数
        echo $is_args;
        echo $document_root;
        echo $document_uri;
        echo $host;
        echo $remote_port;
        echo $remote_user;
        echo $request_method;
        echo $request_filename;
        echo $request_uri;
        echo $scheme;
        echo $server_protocol;
        echo $server_addr;
        echo $server_name;
        echo $server_port; #服务器被访问的端口
        echo $http_user_agent; #浏览器信息
        echo $http_cookie; #
        echo $cookie_key2;
        set $timinglee lee;
        echo $timinglee;
    }

rewrite模块

if指令

  • = #比较变量和字符串是否相等,相等时if指令认为该条件为true,反之为false
  • != #比较变量和字符串是否不相等,不相等时if指令认为条件为true,反之为false
  • ~ #区分大小写字符,可以通过正则表达式匹配,满足匹配条件为真,不满足匹配条件为假
  • !~ #区分大小写字符,判断是否匹配,不满足匹配条件为真,满足匹配条件为假
  • ~* #不区分大小写字符,可以通过正则表达式匹配,满足匹配条件为真,不满足匹配条件为假
  • !~* #不区分大小字符,判断是否匹配,满足匹配条件为假,不满足匹配条件为真
  • -f 和 !-f #判断请求的文件是否存在和是否不存在
  • -d 和 !-d #判断请求的目录是否存在和是否不存在
  • -x 和 !-x #判断文件是否可执行和是否不可执行
  • -e 和 !-e #判断请求的文件或目录是否存在和是否不存在(包括文件,目录,软链接)

#注意:

#如果$变量的值为空字符串或0,则if指令认为该条件为false,其他条件为true。

#nginx 1.0.1之前$变量的值如果以0开头的任意字符串会返回false

location /test2 {
    if ( !-e $request_filename ){ #当访问test2时判断是否存在,不存在就符合
        echo "$request_filename is not exist";
          }
    }

set,break指令

location /break {
        default_type text/html;
        set $name lee;  #设定变量,成功设定后就能使用
        echo $name;
        if ( $http_user_agent = "curl/7.76.1" ){
            break; # 在location中遇到break后,之后的动作就不再执行
        }
        set $id 666;
        echo $id;
    }

return指令

表示完成请求后的状态码可以是可以自定义的

location /return {
        default_type text/html;
        if ( !-e $request_filename){
            return 301 http://www.baidu.com; #判断访问的文件是否存在,不存在就返回301的状态码并定向到baidu上
        }
        echo "$request_filename is exist";
    }

rewrite指令

通过正则表达式的匹配来改变uri,可以同时存在一个或多个指令,按顺序依次对uri匹配

#语法格式
rewrite regex replacement [flag];

flag说明

redirect;
#临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URL给客户端
#由客户端重新发起请求;使用相对路径,或者http://或https://开头,状态码:302
#浏览器中不会产生最后的解析信息
permanent;
#重写完成后以永久重定向方式直接返回重写后生成的新URL给客户端
#由客户端重新发起请求,状态码:301
#浏览器中会存放解析信息
break;
#重写完成后,停止对当前URL在当前location中后续的其它重写操作
#而后直接跳转至重写规则配置块之后的其它配置,结束循环,建议在location中使用
#适用于一个URL一次重写
last;
#重写完成后,停止对当前URI在当前location中后续的其它重写操作,
#而后对新的URL启动新一轮重写检查,不建议在location中使用
#适用于一个URL多次重写,要注意避免出现超过十次以及URL重写后返回错误的给用户
#redirect与permanent
[root@nginx-node1 conf.d] mkdir /data/web/var -p
[root@nginx-node1 conf.d] echo var page > /data/web/var/index.html
[root@nginx-node1 conf.d] vim /usr/local/nginx/conf.d/vars1.conf 
[root@nginx-node1 conf.d] curl var.timinglee.org
var page
[root@nginx-node1 conf.d] curl www.timinglee.org
www.timinglee.org

[root@nginx-node1 conf.d] vim /usr/local/nginx/conf.d/vars1.conf
 location / {
        root /data/web/var;
        index index.html;
        #rewrite / http://www.timinglee.com permanent;
        #rewrite / http://www.timinglee.com redirect;
    }
#打开rewrite-permanent,若打开redirect则显示302
location / {
        root /data/web/var;
        index index.html;
        rewrite / http://www.timinglee.com permanent;
        #rewrite / http://www.timinglee.com redirect;
    }
[root@nginx-node1 conf.d] vim /usr/local/nginx/conf.d/vars1.conf 
[root@nginx-node1 conf.d] nginx -s reload
[root@nginx-node1 conf.d] curl var.timinglee.org
<html>
<head><title>301 Moved Permanently</title></head> #成功显示,curl不支持重定向
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.26.2</center>
</body>
</html>

#break与last
[root@nginx-node1 conf.d] mkdir /data/web/html/{test1,test2,break,last} -p
[root@nginx-node1 conf.d] echo test1 > /data/web/html/test1/index.html
[root@nginx-node1 conf.d] echo test2 > /data/web/html/test2/index.html
[root@nginx-node1 conf.d] echo break > /data/web/html/break/index.html
[root@nginx-node1 conf.d] echo last > /data/web/html/last/index.html
[root@nginx-node1 conf.d] vim vars1.conf
 location /break {
                rewrite ^/break/(.*) /test1/$1;
                rewrite ^/test1/(.*) /test2/$1;
        }       
      location /last {
                rewrite ^/last/(.*) /test1/$1;
                rewrite ^/test1/(.*) /test2/$1;/
        }
      location /test1 {
                default_type text/html;
                echo "timinglee hahahaahaha";
        }
      location /test2 {
                root /data/web/html;
        }

rewrite案例:实现自动跳转https

[root@nginx-node1 ~] vim /usr/local/nginx/conf.d/vhost.conf
server {
        listen 80;
        server_name www.timinglee.org;
        root /data/web/html;
        index index.html;
        listen 443 ssl;
        ssl_certificate /usr/local/nginx/certs/timinglee.org.crt;
        ssl_certificate_key /usr/local/nginx/certs/timinglee.org.key;
        ssl_session_cache       shared:SSL:1m;
        ssl_session_timeout     5m; #全站加密

        location / {
                if ( $scheme = http ){ #判断是否有http,如果没有则直接重定向到主目录,此处时www.timinglee.org
                        rewrite /(.*) https://$host/$1 redirect;
                }
                if ( !-e $request_filename ){ #判断是否有输入的这个文件,没有则重定向到主目录
                        rewrite /(.*) https://$host/index.html redirect;
                }

        }
}

在这里插入图片描述

在这里插入图片描述

nginx防盗链

1.实验前准备
[root@nginx-node1 conf.d] mkdir /data/web/html/images
#将主网页图片放入images中,盗链图片放在 /data/web/html中
#准备一台虚拟机,上面安装好http服务
[root@aaa ~] vim  /var/www/html/index.html
[root@aaa ~] cat /var/www/html/index.html 
<html>

  <head>
    <meta http-equiv=Content-Type content="text/html;charset=utf-8">
    <title>盗链</title>
</head>

  <body>
    <img src="http://www.timinglee.org/images/lee.png" >
    <h1 style="color:red">欢迎大家</h1>
    <p><a href=http://www.timinglee.org>狂点老李</a>出门见喜</p>
  </body>

</html>

在这里插入图片描述

此图片为timinglee上的图片,被盗用,链接点击也是访问timinglee

2.referer

防盗链是基于客户端携带的referer实现,记录打开一个页面之前的记录是从哪个页面跳转过来的标记信息。如果只是链接了自己网站的图片或者单独的资源而不是打开整个网页就属于盗链

[root@nginx-node1 html] tail /usr/local/nginx/logs/access.log  #查看referer信息
172.25.254.1 - - [18/Aug/2024:23:53:39 +0800] "GET /images/lee.png HTTP/1.1" 200 9285 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0" #本访问方式没有referer
172.25.254.1 - - [19/Aug/2024:00:00:55 +0800] "GET /images/lee.png HTTP/1.1" 304 0 "https://www.baidu.com/s? wd=www.timinglee.org%2Fimages%2Flee.png&rsv_spt=1&rsv_iqid=0xa495251d06cfd9c0&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_dl=ib&rsv_sug3=34&rsv_enter=1" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0" #可以看见referer为从百度来的信息,此方式不为盗链

3.定义防盗链
server {
        listen 80;
        server_name www.timinglee.org;
        root /data/web/html;
        index index.html;
		location /  {
        valid_referers none blocked server_names *.timinglee.org ~/.baidu/.;
        #定义有效的referer为:空,空格或者server_names带有。baidu的信息,
        if ( $invalid_referer ){
                rewrite ^/   http://www.timinglee.org/daolian.png; #其余的重定向到daolian中
        }

    }

在这里插入图片描述

  • 22
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值