高性能 Web 服务器:让网页瞬间绽放的魔法引擎(中)

目录

一.Nginx版本和安装方式:源码编译安装

 1.验证版本及编译参数

2.使用安装完成的二进制文件nginx

3.Nginx 启动文件

二.平滑升级和回滚

三.全局配置 实现 nginx 的高并发配置

四.核心配置:新建一个 PC web 站点

五.核心配置:location的详细使用

1.精确匹配

2.匹配URI开始区分大小写

3.匹配URI开始不区分大小写

4.文件名后缀

5.优先级

六.核心配置:Nginx 账户认证功能

七.核心配置:自定义错误页面

八.核心配置:自定义错误日志

九.核心配置:检测文件是否存在

十.核心配置:长连接配置

十一.核心配置:作为下载服务器配置

十二.高级配置:Nginx 状态页

十三.高级配置:Nginx 压缩功能

十四.高级配置:Nginx Nginx 变量使用

1.内置变量

2.自定义变量

十五.Nginx Rewrite 相关功能

1.ngx_http_rewrite_module 模块指令: if 指令

2.ngx_http_rewrite_module 模块指令:break指令

3.ngx_http_rewrite_module 模块指令:return指令

4.ngx_http_rewrite_module 模块指令:set 指令

5.rewrite 指令:域名永久与临时重定向

6.rewrite 指令:break 与 last

7.rewrite 指令:自动跳转 https

8.rewrite 指令:判断文件是否存在

9.Nginx 防盗链


一.Nginx版本和安装方式:源码编译安装

Nginx版本;Mainline version 主要开发版本,一般为奇数版本号,比如1.19;Stable version 当前最新稳定版,一般为偶数版本,如:1.20;Legacy versions 旧的稳定版,一般为偶数版本,如:1.18;Nginx安装可以使用yum或源码安装,但是推荐使用源码编译安装 yum的版本比较旧;编译安装可以更方便自定义相关路径;使用源码编译可以自定义相关功能,更方便业务的上的使用。

#在nginx.org选择稳定版下载源码包安装:nginx-1.24.0.tar.gz和nginx-1.26.0.tar.gz
[root@Nginx ~]# dnf install gcc pcre-devel zlib-devel openssl-devel -y
[root@Nginx ~]# tar zxf nginx-1.24.0.tar.gz
[root@Nginx ~]# cd nginx-1.24.0/
[root@Nginx nginx-1.24.0]# useradd -s /sbin/nologin -M nginx
[root@Nginx nginx-1.24.0]# ls
auto CHANGES.ru configure html Makefile objs src
CHANGES conf contrib LICENSE man README
[root@Nginx nginx-1.24.0]# ./configure --prefix=/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 ~]# ./nginx
[root@nginx ~]# ps aux | grep nginx
root       41085  0.0  0.0   9840   924 ?        Ss   20:53   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      41086  0.0  0.1  13700  4756 ?        S    20:53   0:00 nginx: worker process
root       41146  0.0  0.0 221668  2324 pts/0    S+   22:09   0:00 grep --color=auto nginx
[root@nginx ~]# netstat -antlupe | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      0          70327      41085/nginx: master 
#/usr/local/nginx/sbin/nginx -s stop         #关闭nginx
#/usr/local/nginx/sbin/nginx -s restart      #开启nginx
[root@Nginx nginx-1.24.0]# vim auto/cc/gcc   #关闭debug功能	
	....
	#debug
	#CFLAGS="$CFLAGS -g"
	.....
[root@Nginx nginx-1.24.0]# make && make install
 1.验证版本及编译参数
[root@nginx ~]# vim ~/.bash_profile   #添加环境变量,可以直接用。
	....
	export PATH=$PATH:/usr/local/nginx/sbin
[root@nginx ~]# source ~/.bash_profile  #生效一下
[root@nginx ~]# nginx
[root@nginx ~]# nginx -V
nginx version: nginx/1.24.0
built by gcc 11.4.1 20231218 (Red Hat 11.4.1-3) (GCC)
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: --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 ~]# curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Thu, 15 Aug 2024 14:21:03 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Thu, 15 Aug 2024 12:00:45 GMT
Connection: keep-alive
ETag: "66bdeded-267"
Accept-Ranges: bytes
2.使用安装完成的二进制文件nginx
[root@Nginx ~]# nginx -v
nginx version: nginx/1.18.0
-V #显示版本和编译参数
-t #测试配置文件是否异
-T #测试并打印
-q #静默模式
-s stop, quit, reopen, reload #
发送信号,reload信号 会生成新的worker,但master不会重新生成
-p prefix : set prefix path (default: /etc/nginx/) #指定Nginx 目录
-c filename : set configuration file (default: /etc/nginx/nginx.conf) #
配置文件路径

[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
nginx: [emerg] "worker_processes" directive is duplicate in
/usr/local/nginx/conf/nginx.conf:3
root@Nginx ~]# nginx -g "worker_processes 6;"
[root@nginx ~]# ps aux | grep nginx
root       41085  0.0  0.0   9840  2672 ?        Ss   20:53   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      41172  0.0  0.1  13700  4756 ?        S    22:46   0:00 nginx: worker process
root       41181  0.0  0.0 221668  2212 pts/0    S+   22:50   0:00 grep --color=auto nginx
[root@Nginx ~]# nginx -s quit    #如果出现pid后缀的情况报错就reboot
[root@Nginx ~]# ps aux | grep nginx
root 48171 0.0 0.1 221664 2176 pts/0 S+ 14:04 0:00 grep --
color=auto nginx
#前台运行
[root@Nginx ~]# nginx -g "daemon off;"
3.Nginx 启动文件
[root@Nginx ~]# nginx
[root@Nginx ~]# 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 ExecStop=/bin/kill -s QUIT $MAINPID PrivateTmp=true 

[Install] 
WantedBy=multi-user.target 
[root@Nginx ~]# systemctl daemon-reload 
[root@Nginx ~]# systemctl enable --now nginx
[root@Nginx ~]# ps aux | grep nginx
#如果出现错误查看端口netstat -tunlp | grep 80,把占用的全杀了kill -9 

二.平滑升级和回滚

[root@nginx ~]# ls
anaconda-ks.cfg  echo-nginx-module-0.63.tar.gz  nginx-1.26.1         Templates
Desktop          Music                          nginx-1.26.1.tar.gz  Videos
Documents        nginx-1.24.0                   Pictures
Downloads        nginx-1.24.0.tar.gz            Public
[root@nginx ~]# tar zxf echo-nginx-module-0.63.tar.gz 
[root@nginx ~]# ls
anaconda-ks.cfg  echo-nginx-module-0.63         nginx-1.24.0.tar.gz  Public
Desktop          echo-nginx-module-0.63.tar.gz  nginx-1.26.1         Templates
Documents        Music                          nginx-1.26.1.tar.gz  Videos
Downloads        nginx-1.24.0                   Pictures
[root@nginx ~]# tar zxf nginx-1.26.1.tar.gz 
[root@nginx ~]# cd nginx-1.26.1/     #开始编译新版本 
[root@Nginx nginx-1.26.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --add-module=/root/memc-nginx-module-0.20 --add-module=/root/srcache-nginx-module-0.33 --add-module=/root/echo-nginx-module-0.63 --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      #只要make无需要make install
[root@Nginx nginx-1.26.1]# make   #查看两个版本 
[root@Nginx nginx-1.26.1]# ll objs/nginx /usr/local/nginx/sbin/nginx -rwxr-xr-x 1 root root 1239416 Jul 18 15:08 objs/nginx -rwxr-xr-x 1 root root 5671488 Jul 18 11:41 /usr/local/nginx/sbin/nginx     #把之前的旧版的nginx命令备份 
[root@Nginx ~]# cd /usr/local/nginx/sbin/ 
[root@Nginx sbin]# cp nginx nginx.24     #把新版本的nginx命令复制过去 
[root@Nginx sbin]# \cp -f /root/nginx/nginx-1.26.1/objs/nginx /usr/local/nginx/sbin #检测一下有没有问题 
[root@Nginx 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 
[root@nginx sbin]# kill -USR2 41085   #nginx worker ID #USR2 平滑升级可执行程序,将存储有旧版本主进程PID的文件重命名为nginx.pid.oldbin,并启动新的 nginx #此时两个master的进程都在运行,只是旧的master不在监听,由新的master监听80 #此时Nginx开启一个新的master进程,这个master进程会生成新的worker进程,这就是升级后的Nginx进 程,此时老的进程不会自动退出,但是当接收到新的请求不作处理而是交给新的进程处理。
[root@nginx sbin]# ps aux | grep nginx
root       41085  0.0  0.0   9840  2672 ?        Ss   20:53   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      41086  0.0  0.1  13700  4756 ?        S    20:53   0:00 nginx: worker process
root       41163  0.0  0.1   9840  6068 ?        S    22:41   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      41164  0.0  0.1  13700  4740 ?        S    22:41   0:00 nginx: worker process
root       41166  0.0  0.0 221668  2220 pts/0    S+   22:41   0:00 grep --color=auto nginx
[root@Nginx sbin]# curl -I localhost HTTP/1.1 200 OK Server: nginx/1.24.0 ##依旧是旧版本生生效 Date: Thu, 18 Jul 2024 07:45:58 GMT Content-Type: text/html Content-Length: 615 Last-Modified: Thu, 18 Jul 2024 03:41:13 GMT Connection: keep-alive ETag: "66988ed9-267" Accept-Ranges: bytes #回收旧版本 
[root@nginx ~]# kill -WINCH 41085
[root@nginx ~]# ps aux | grep nginx
root       41085  0.0  0.0   9840  2672 ?        Ss   20:53   0:00 nginx: master process /usr/local/nginx/sbin/nginx
root       41163  0.0  0.1   9840  6068 ?        S    22:41   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      41164  0.0  0.1  13700  4740 ?        S    22:41   0:00 nginx: worker process
root       41169  0.0  0.0 221668  2276 pts/0    S+   22:44   0:00 grep --color=auto nginx
[root@Nginx sbin]# curl -I 172.25.254.100
HTTP/1.1 200 OK Server: nginx/1.26.1 #新版本生效 Date: Thu, 18 Jul 2024 07:59:45 GMT Content-Type: text/html Content-Length: 615 Last-Modified: Thu, 18 Jul 2024 03:41:13 GMT Connection: keep-alive ETag: "66988ed9-267" Accept-Ranges: bytes #回滚 #如果升级的版本发现问题需要回滚,可以重新拉起旧版本的worker,后续用的是26版本的。
[root@Nginx sbin]# cp nginx nginx.26 
[root@Nginx sbin]# ls 
nginx nginx.24 nginx.26 
[root@Nginx sbin]# \CP -F nginx.24 nginx 
[root@nginx sbin]# kill -HUP 41085
[root@nginx sbin]# ps aux | grep nginx
root       41085  0.0  0.0   9840  2672 ?        Ss   20:53   0:00 nginx: master process /usr/local/nginx/sbin/nginx
root       41163  0.0  0.1   9840  6068 ?        S    22:41   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      41164  0.0  0.1  13700  4740 ?        S    22:41   0:00 nginx: worker process
nginx      41172  0.0  0.1  13700  4756 ?        S    22:46   0:00 nginx: worker process
root       41174  0.0  0.0 221668  2420 pts/0    S+   22:46   0:00 grep --color=auto nginx
[root@nginx sbin]# kill -WINCH 41163
[root@nginx sbin]# ps aux | grep nginx
root       41085  0.0  0.0   9840  2672 ?        Ss   20:53   0:00 nginx: master process /usr/local/nginx/sbin/nginx
root       41163  0.0  0.1   9840  6068 ?        S    22:41   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      41172  0.0  0.1  13700  4756 ?        S    22:46   0:00 nginx: worker process
root       41176  0.0  0.0 221668  2360 pts/0    S+   22:47   0:00 grep --color=auto nginx
[root@nginx sbin]# curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Thu, 15 Aug 2024 14:48:30 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Thu, 15 Aug 2024 12:00:45 GMT
Connection: keep-alive
ETag: "66bdeded-267"
Accept-Ranges: bytes
[root@nginx sbin]# kill -9 41163
[root@nginx sbin]# ps aux | grep nginx
root       41085  0.0  0.0   9840  2672 ?        Ss   20:53   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      41172  0.0  0.1  13700  4756 ?        S    22:46   0:00 nginx: worker process
root       41181  0.0  0.0 221668  2212 pts/0    S+   22:50   0:00 grep --color=auto nginx

三.全局配置 实现 nginx 的高并发配置

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
user  nginx;
worker_processes auto;
worker_cpu_affinity 0001 0010;   #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;   #压力测试之前可以先不改。
}
.....
[root@nginx ~]# nginx -s reload

[root@nginx ~]# sudo -u nginx ulimit -n
1024
[root@nginx ~]# vim /etc/security/limits.conf
.....
# End of file
nginx            -       nofile          100000
[root@nginx ~]# sudo -u nginx ulimit -n
100000
[root@nginx ~]# vim /etc/security/limits.conf
....
#nginx      nofile         100000      #先注释掉用测试工具试一下。有没有出错的。
[root@nginx ~]# dnf install httpd-tools -y  #压力测试工具
[root@nginx ~]# ab -n 10000 -c 5000 http://172.25.254.100/index.html

四.核心配置:新建一个 PC web 站点

root:指定web的家目录,在定义location的时候,文件的绝对路径等于 root+location

alias:定义路径别名,会把访问的路径重新定义到其指定的路径,文档映射的另一种机制;仅能用于 location上下文,此指令使用较少。

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
...
events {
    worker_connections  100000;
    use epoll;
}
...
    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    include "/usr/local/nginx/conf.d/*.conf";   #定义子配置文件路径 
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.
...
[root@nginx ~]# mkdir -p /usr/local/nginx/conf.d
#创建虚拟主机网站配置
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;    
	root /data/web/html;
	index index.html;
}
[root@nginx ~]# mkdir -p /data/web/html
[root@nginx ~]# echo nginx.timinglee.org - 172.25.254.100 > /data/web/html/index.html
[root@nginx ~]# nginx -t
[root@nginx ~]# nginx -s reload
#要在浏览器上访问需要再Windows本地加解析。
测试:[root@nginx ~]# curl 172.25.254.100
nginx.timinglee.org - 172.25.254.100 #浏览器访问或者curl一下

#访问其他路径:root和alias
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;
	root /data/web/html;
	index index.html;
	location /test1/ {
		root /data/web;
	}
}
[root@nginx ~]# mkdir -p /data/web/test1
[root@nginx ~]# echo test1 - 172.25.254.100 > /data/web/test1/index.html
[root@nginx ~]# nginx -t
[root@nginx ~]# nginx -s reload
[root@nginx ~]# curl 172.25.254.100/test1/
test1 - 172.25.254.10

#加alias别名
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;
	root /data/web/html;
	index index.html;
	location /test1/ {
		root /data/web;
	}
	location /test2 {    #注意about后不要加/   #使用alias的时候uri后面如果加了斜杠,则下面的路径配置必须加斜杠,否则403
		alias /data/web/test1;   #类似软链接
	}
}
[root@nginx ~]# nginx -s reload
测试:[root@nginx ~]# curl 172.25.254.100/test2/
test1 - 172.25.254.100
排错看日志:tail /usr/local/nginx/logs/error.log

五.核心配置:location的详细使用

在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射; ngnix会根据用户请求的URI来检查定义的所有location,按一定的优先级找出一个最佳匹配, 而后应用其配置在没有使用正则表达式的时候,nginx会先在server中的多个location选取匹配度最高的一个uri,是用户请求的字符串,即域名后面的web文件路径;然后使用该location模块中的正则url和字符串,如果匹配成功就结束搜索,并使用此location处理 此请求。

#语法规则:
= #用于标准uri前,需要请求字串与uri精确匹配,大小敏感,如果匹配成功就停止向下匹配并立
即处理请求
^~ #用于标准uri前,表示包含正则表达式,并且匹配以指定的正则表达式开头
#对uri的最左边部分做匹配检查,不区分字符大小写
~ #用于标准uri前,表示包含正则表达式,并且区分大小写
~* #用于标准uri前,表示包含正则表达式,并且不区分大写
不带符号 #匹配起始于此uri的所有的uri
\ #用于标准uri前,表示包含正则表达式并且转义字符。可以将 . * ?等转义为普通符号
#匹配优先级从高到低:
 ~/~*, 不带符号,^~,=

1.精确匹配

在server部分使用location配置一个web界面,例如:当访问nginx 服务器的时候要显示指定 html文件的内容,精确匹配一般用于匹配组织的logo等相对固定的URL,匹配优先级最高。

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;
	root /data/web/html;
	index index.html;
	location /test {
		root /data/web1;
	}
}
[root@nginx ~]# nginx -s reload
[root@nginx ~]# mkdir -p /data/web/test1
[root@nginx ~]# echo test1 page > /data/web1/test1/index.html
[root@nginx ~]# tail /usr/local/nginx/logs/error.log
测试:浏览器访问nginx.timinglee.org/test1
#浏览器要访问域名需要再Windows本地加解析。关闭防火墙和selinux。
2.匹配URI开始区分大小写

~ 实现区分大小写的模糊匹配.因为 ~ 区分大小写,当用户的请求被执行匹配时发现location中定义的是小写的html, 本次访问的uri匹配失败,后续要么继续往下匹配其他的location(如果有),要么报错给客户端。

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;
	root /data/web/html;
	index index.html;
	location /test1/ {
		root /data/web1;
	}
	location ^~ /t {   #以t开头的
		root /data/web2;
	}
	location ~ \.html$ {   #以html结尾的
		root /data/web3;
	}
}
[root@nginx ~]# nginx -s reload
[root@nginx ~]# mkdir -p /data/web/test2
[root@nginx ~]# echo test2 page > /data/web2/test2/index.html
[root@nginx ~]# mkdir -p /data/web/test3
[root@nginx ~]# echo test3 page > /data/web3/test3/index.html
[root@nginx ~]# tail /usr/local/nginx/logs/error.log
测试:浏览器访问nginx.timinglee.org/test2
访问nginx.timinglee.org/test3
#浏览器要访问域名需要再Windows本地加解析。关闭防火墙和selinux。
3.匹配URI开始不区分大小写

~* 用来对用户请求的uri做模糊匹配,uri中无论都是大写、都是小写或者大小写混合,此模式也都会匹配,通常使用此模式匹配用户request中的静态资源并继续做下一步操作,此方式使用较多。

[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;
	root /data/web/html;
	index index.html;
	location /test1/ {
		root /data/web1;
	}
	location ^~ /t {   #以t开头的
		root /data/web2;
	}
	location ~* \.HTML$ {   #以html结尾的,不区分大小写
		root /data/web3;
	}
}
[root@nginx ~]# nginx -s reload
[root@nginx ~]# tail /usr/local/nginx/logs/error.log
测试:浏览器访问nginx.timinglee.org/test3
#浏览器要访问域名需要再Windows本地加解析。关闭防火墙和selinux。
4.文件名后缀
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;
	root /data/web/html;
	index index.html;
	location /test1/ {
		root /data/web1;
	}
	location ^~ /t {   #以t开头的
		root /data/web2;
	}
	location ~* \.(HTML|lee)$ {   #以html和lee结尾的,不区分大小写
		root /data/web3;
	}
}
[root@nginx ~]# nginx -s reload
[root@nginx ~]# echo test4 index.lee > /data/web3/test3/index.lee
[root@nginx ~]# tail /usr/local/nginx/logs/error.log
测试:浏览器访问nginx.timinglee.org/lee/index.html和nginx.timinglee.org/lee/index.lee
#浏览器要访问域名需要再Windows本地加解析。关闭防火墙和selinux。
5.优先级
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;
	root /data/web/html;
	index index.html;
	location = /test {
		root /data/web2;
	}
	location /test {
		root /data/web1;
	}
	location ^~ /t {
		root /data/web3;
	}
	location ~* /TES {
		root /data/web5;
	} 
	location ~ /tes {
		root /data/web4;
	}
}
[root@nginx ~]# nginx -s reload
mkdir -p /data/web{1..5}
mkdir -p /data/web{1..5}/test
echo web1 - 172.25.254.100 > /data/web1/test/index.html
echo web2 - 172.25.254.100 > /data/web2/test/index.html
echo web3 - 172.25.254.100 > /data/web3/test/index.html
echo web4 - 172.25.254.100 > /data/web4/test/index.html
echo web5 - 172.25.254.100 > /data/web5/test/index.html
测试:浏览器访问nginx.timinglee.org/test。先依次注释掉要测试的优先级,在浏览器访问看效果。 最后优先级的顺序如下:~/~*, 不带符号,^~,=
#浏览器要访问域名需要再Windows本地加解析。关闭防火墙和selinux。

六.核心配置:Nginx 账户认证功能

[root@nginx ~]# htpasswd -cm /usr/local/nginx/.htpasswd xiaofeifei
New password: redhat
Re-type new password: redhat
Adding password for user xiaofeifei
[root@nginx ~]# htpasswd -m /usr/local/nginx/.htpasswd zhuzhuxia
New password: redhat
Re-type new password: redhat 
Adding password for user zhuzhuxia
[root@nginx ~]# cat /usr/local/nginx/.htpasswd 
xiaofeifei:$apr1$IhO5VvyN$uwQXftSoReS6u88fhl5rm/
zhuzhuxia:$apr1$3mOMRGDR$eLLT2sLGw6ItP6rZPWCkW/
[root@nginx ~]# mkdir -p /data/web/zhuzhuxia
[root@nginx ~]# mkdir -p /data/web/xiaofeifei
[root@nginx ~]# echo zhuzhuxia si joker - 172.25.254.100 > /data/web/zhuzhuxia/index.html
[root@nginx ~]# echo xiaofeifei ye si joker - 172.25.254.100 > /data/web/xiaofeifei/index.html
[root@nginx ~]# cat /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;
	root /data/web/html;
	index index.html;
	location /test1/ {
		root /data/web;
	}
	location /test2 {
		alias /data/web/test1;
	}
	location /zhuzhuxia {
		root /data/web;
		auth_basic "login password !!!!";
		auth_basic_user_file "/usr/local/nginx/.htpasswd";
	}
	location /xiaofeifei {
		root /data/web;
		auth_basic "login password !!!!";
		auth_basic_user_file "/usr/local/nginx/.htpasswd";
	}
}

[root@nginx ~]# nginx -s reload
测试:在浏览器里输入172.25.254.100/zhuhzuxia有弹窗就对了。或者是curl
[root@nginx ~]# curl 172.25.254.100/xiaofeifei/ -u xiaofeifei:redhat
xiaofeifei ye si joker - 172.25.254.100
[root@nginx ~]# curl 172.25.254.100/zhuzhuxia/ -u xiaofeifei:redhat
zhuzhuxia si joker - 172.25.254.100

七.核心配置:自定义错误页面

自定义错误页,同时也可以用指定的响应状态码进行响应, 可用位置:http, server, location, if in location。

[root@nginx ~]# cat /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;
	root /data/web/html;
	index index.html;
	error_page 404 /40x.html; 
	location = /40x.html {
		root /data/web/errorpage;
	}
	location /zhuzhuxia {
		root /data/web;
		auth_basic "login password !!!!";
		auth_basic_user_file "/usr/local/nginx/.htpasswd";
	}
....
}
[root@Nginx ~]# mkdir -p /data/web/errorpage
[root@Nginx ~]# echo sorry error page - 172.25.254.100 > /data/web/errorpage/40x.html
[root@nginx ~]# nginx -s reload
测试:[root@nginx ~]# curl 172.25.254.100/1
sorry error page - 172.25.254.100

八.核心配置:自定义错误日志

[root@nginx ~]# mkdir -p /var/log/timinglee.org
[root@nginx ~]# cat /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;
	root /data/web/html;
	index index.html;
	error_page 404 /40x.html; 
	error_log /var/log/timinglee.org/error.log;
	access_log /var/log/timinglee.org/access.log;
	location = /40x.html {
		root /data/web/errorpage;
	}
	location /zhuzhuxia {
		root /data/web;
		auth_basic "login password !!!!";
		auth_basic_user_file "/usr/local/nginx/.htpasswd";
	}
....
}
[root@nginx ~]# nginx -s reload
测试:
[root@nginx ~]# curl 172.25.254.100/aaa
sorry error page - 172.25.254.100
[root@nginx ~]# cat /var/log/timinglee.org/error.log 
2024/08/16 14:30:18 [error] 41851#0: *38 open() "/data/web/html/aaa" failed (2: No such file or directory), client: 172.25.254.100, server: www.timinglee.org, request: "GET /aaa HTTP/1.1", host: "172.25.254.100"
[root@nginx ~]# cat /var/log/timinglee.org/access.log 
172.25.254.100 - - [16/Aug/2024:14:30:18 +0800] "GET /aaa HTTP/1.1" 404 34 "-" "curl/7.76.1"

九.核心配置:检测文件是否存在

try_files会按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹),如 果所有文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一 个内部重定向,之前的参数只设置内部URI的指向。最后一个参数是回退URI且必须存在,否则会出现内 部500错误。

[root@nginx ~]# mkdir -p /data/web/html/error
[root@nginx ~]# echo error default - 172.25.254.100 > /data/web/html/error/default.html
[root@nginx ~]# cat /usr/local/nginx/conf.d/vhost.conf
server {
	listen 80;
	server_name nginx.timinglee.org;
	root /data/web/html;
	index index.html;
	error_page 404 /40x.html; 
	error_log /var/log/timinglee.org/error.log;
	access_log /var/log/timinglee.org/access.log;
	try_files $uri $uri.html $uri/index.html /error/default.html;
	location = /40x.html {
		root /data/web/errorpage;
	}
	location /zhuzhuxia {
		root /data/web;
		auth_basic "login password !!!!";
		auth_basic_user_file "/usr/local/nginx/.htpasswd";
	}
....
}
[root@nginx ~]# nginx -s reload
测试:
[root@nginx ~]# curl nginx.timinglee.org/error
error default - 172.25.254.100
[root@nginx ~]# cat /var/log/timinglee.org/access.log 
172.25.254.100 - - [16/Aug/2024:14:57:31 +0800] "GET /error HTTP/1.1" 200 31 "-" "curl/7.76.1"

十.核心配置:长连接配置

[root@nginx ~]# yum install telnet -y  #长链接测试工具
[root@nginx ~]# curl -v nginx.timinglee.org
*   Trying 172.25.254.100:80...
* Connected to nginx.timinglee.org (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: nginx.timinglee.org
> User-Agent: curl/7.76.1
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.24.0
< Date: Fri, 16 Aug 2024 06:55:58 GMT
< Content-Type: text/html
< Content-Length: 37
< Last-Modified: Fri, 16 Aug 2024 06:45:28 GMT
< Connection: keep-alive
< Keep-Alive: timeout=60
< ETag: "66bef588-25"
< Accept-Ranges: bytes
< 
nginx.timinglee.org - 172.25.254.100
* Connection #0 to host nginx.timinglee.org left intact
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
...
    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65 60;
    keepalive_requests  500;
...
[root@nginx ~]# nginx -s reload
[root@nginx ~]# telnet nginx.timinglee.org 80
Trying 172.25.254.100...
Connected to nginx.timinglee.org.
Escape character is '^]'.
GET / HTTP/1.1    ##输入动作
Host: nginx.timinglee.org  #输入访问HOST,回车

HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Fri, 16 Aug 2024 07:13:29 GMT
Content-Type: text/html
Content-Length: 37
Last-Modified: Fri, 16 Aug 2024 06:45:28 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "66bef588-25"
Accept-Ranges: bytes

nginx.timinglee.org - 172.25.254.100
GET / HTTP/1.1     ##第二次操作
Host: nginx.timinglee.org   #第二次操作

HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Fri, 16 Aug 2024 07:13:37 GMT
Content-Type: text/html
Content-Length: 37
Last-Modified: Fri, 16 Aug 2024 06:45:28 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "66bef588-25"
Accept-Ranges: bytes

nginx.timinglee.org - 172.25.254.100
Connection closed by foreign host.  #自动断开链接

十一.核心配置:作为下载服务器配置

ngx_http_autoindex_module 模块处理以斜杠字符 "/" 结尾的请求,并生成目录列表,可以做为下载服务 配置使用

[root@Nginx ~]# mkdir -p /data/web/download
[root@Nginx ~]# dd if=/dev/zero of=/data/web/download/leefile bs=1M count=100
[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf	
....
     location /download {
                root /data/web;
                autoindex on; #自动索引功能
                autoindex_exact_size off;  #计算文件确切大小(单位bytes),此为默认值,off只显示
大概大小(单位kb、mb、gb)
                autoindex_localtime on; #on表示显示本机时间而非GMT(格林威治)时间,默为为off显
示GMT时间
                limit_rate 1024k;#限速,默认不限速
        }
...
[root@nginx ~]# nginx -s reload
测试:
发我浏览器:curl nginx.timing.org/download/
[root@nginx ~]# wget nginx.timinglee.org/download/
--2024-08-16 16:43:46--  http://nginx.timinglee.org/download/
Resolving nginx.timinglee.org (nginx.timinglee.org)... 172.25.254.100
Connecting to nginx.timinglee.org (nginx.timinglee.org)|172.25.254.100|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: ‘index.html.3’

index.html.3            [ <=>               ]     253  --.-KB/s    in 0s      

2024-08-16 16:43:46 (38.2 MB/s) - ‘index.html.3’ saved [253]
#重启Nginx并访问测试下载页面

十二.高级配置:Nginx 状态页

[root@nginx ~]# cat /usr/local/nginx/conf.d/zhuzhuxia.conf
server {
	listen 80;
	server_name status.timinglee.org;
	root /data/web/html;
	index index.html;
	location /status {
		stub_status;
		allow 172.25.254.1;
		deny all;
	}
}
[root@nginx ~]# nginx -s reload
测试:在浏览器输入status.timinglee.org/status/会出现以下内容
Active connections: 2                #当前处于活动状态的客户端连接数
                                     #包括连接等待空闲连接数=reading+writing+waiting
server accepts handled requests       #accepts:统计总值,Nginx自启动后已经接受的客户端请求连接的总数。
#handled统计总值,Nginx自启动后已经处理完成的客户端请求连接总数#handled通常等于accepts,除非有因worker_connections限制等被拒绝的连接
#requests统计总值,Nginx自启动后客户端发来的总的请求数
 67 67 76 
Reading: 0 Writing: 1 Waiting: 1    #当前状态,正在读取客户端请求报文首部的连接的连接数
#数值越大,说明排队现象严重,性能不足

十三.高级配置:Nginx 压缩功能

Nginx支持对指定类型的文件进行压缩然后再传输给客户端,而且压缩还可以设置压缩比例,压缩后的文 件大小将比源文件显著变小,样有助于降低出口带宽的利用率,降低企业的IT支出,不过会占用相应的CPU资源。 Nginx对文件的压缩功能是依赖于模块 ngx_http_gzip_module,默认是内置模块。

[root@nginx ~]# echo small - 172.25.254.100 > /data/web/html/small.html
[root@nginx ~]# du -sh /usr/local/nginx/logs/access.log 12K	/usr/local/nginx/logs/access.log
[root@nginx ~]# cat /usr/local/nginx/logs/access.log > /data/web/html/big.html
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
....
    keepalive_requests  500;

    gzip  on;     #启用或禁用gzip压缩,默认关闭
    gzip_comp_level 5;   #压缩比由低到高从1到9,默认为1,值越高压缩后文件越小,但是消耗cpu比较高。基本设定未4或者5
    gzip_min_length 1k;  #gzip压缩的最小文件,小于设置值的文件将不会压缩
    gzip_http_version 1.1;   #启用压缩功能时,协议的最小版本,默认HTTP/1.1
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/gif image/png;    #指明仅对哪些类型的资源执行压缩操作;默认为gzip_types text/html,不用显示指定,否则出错
gzip_vary on;   #如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”,一般打开
    include "/usr/local/nginx/conf.d/*.conf";
....
[root@nginx ~]# nginx -s reload
测试:
[root@nginx ~]# curl --head --compressed 172.25.254.100/small.html
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Fri, 16 Aug 2024 08:31:06 GMT
Content-Type: text/html
Content-Length: 23
Last-Modified: Fri, 16 Aug 2024 08:30:58 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "66bf0e42-17"
Accept-Ranges: bytes
[root@nginx ~]# curl --head --compressed 172.25.254.100/big.html
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Fri, 16 Aug 2024 08:31:09 GMT
Content-Type: text/html
Last-Modified: Fri, 16 Aug 2024 08:30:44 GMT
Connection: keep-alive
Keep-Alive: timeout=60
Vary: Accept-Encoding
ETag: W/"66bf0e34-2948"
Content-Encoding: gzip

十四.高级配置:Nginx Nginx 变量使用

nginx的变量可以在配置文件中引用,作为功能判断或者日志等场景使用;变量可以分为内置变量和自定义变量;内置变量是由nginx模块自带,通过变量可以获取到众多的与客户端访问相关的值。

1.内置变量
[root@Nginx ~]# vim /usr/local/nginx/conf.d/xiaofeifei.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 $document_root;   #保存了针对当前资源的请求的系统根目录,例如:/data/web/html.
		echo $document_uri;    #保存了当前请求中不包含参数的URI,注意是不包含请求的指令.
		echo $host;            #存放了请求的host名称.
		echo $remote_port;          #客户端请求Nginx服务器时随机打开的端口,这是每个客户端自己的端口
		echo $remote_user;          #已经经过Auth Basic Module验证的用户名
		echo $request_method;       #请求资源的方式,GET/PUT/DELETE等
		echo $request_filename;     #当前请求的资源文件的磁盘路径,由root或alias指令与URI请求生成的文件绝对路径,
		echo $request_uri;                #包含请求参数的原始URI,不包含主机名,相当于:$document_uri?$args
		echo $scheme;
 		echo $server_protocol;    #保存了客户端请求资源使用的协议的版本,例如:HTTP/1.0,HTTP/1.1,HTTP/2.0等
         echo $server_addr;   #保存了服务器的IP地址
         echo $server_name;    #虚拟主机的主机名
         echo $server_port;     #虚拟主机的端口号
         echo $http_user_agent;   #客户端浏览器的详细信息
         echo $http_cookie;    #客户端的所有cookie信息
         echo $cookie_key2;    #name为任意请求报文首部字部cookie的key名
	}
}
[root@nginx ~]# nginx -s reload
nginx: [emerg] unknown directive "echo" in /usr/local/nginx/conf.d/xiaofeifei.conf:9
#出现问题是在源码安装时没有加echo模块
[root@nginx ~]# vi /etc/hosts  
#添加本地解析var.timinglee.org 172.25.254.100
测试:
[root@nginx ~]# curl var.timinglee.org/var   #$remote_addr;
[root@nginx ~]# curl var.timinglee.org/var?name=lee&&id=6666  #echo $args; $document_root; $document_uri; echo $host; $remote_port; 
[root@nginx ~]# curl -u lee:lee var.timinglee.org/var?name=lee&&id=6666  #$remote_user; $request_method;  $request_filename; $document_uri; $scheme; $server_protocol; $server_addr; $server_name; $server_port; $http_user_agent;
看浏览器版本:rpm -qa | grep curl
[root@nginx ~]# curl -b "key1=lee,key2=timinglee" -u lee:lee var.timinglee.org/var?name=lee&&id=6666   ##$http_cookie;  $cookie_key2;
172.25.254.100
name=lee
?
/data/web/html
/var
var.timinglee.org
47264
lee
GET
/data/web/html/var
/var?name=lee
http
HTTP/1.1
172.25.254.100
var.timinglee.org
80
curl/7.76.1
key1=lee,key2=timinglee
timinglee
lee
2.自定义变量
[root@Nginx ~]# vim /usr/local/nginx/conf.d/xiaofeifei.conf
server {
	listen 80;
	server_name var.timinglee.org;
	root /data/web/html;
	index index.html;
	
	location /var {
		default_type text/html;
		set $timinglee lee;
         echo $timinglee;
	}
}
测试:[root@nginx~]# curl var.timinglee.org/var

十五.Nginx Rewrite 相关功能

Nginx服务器利用 ngx_http_rewrite_module 模块解析和处理rewrite请求 此功能依靠 PCRE(perl compatible regular expression),因此编译之前要安装PCRE库 rewrite是nginx服务器的重要功能之一,用于实现URL的重写,URL的重写是非常有用的功能 比如它可以在我们改变网站结构之后,不需要客户端修改原来的书签,也无需其他网站修改我们的 链接,就可以设置为访问 另外还可以在一定程度上提高网站的安全性。

1.ngx_http_rewrite_module 模块指令: if 指令

用于条件匹配判断,并根据条件判断结果选择不同的Nginx配置,可以配置在server或location块中进行 配置,Nginx的if语法仅能使用if做单次判断,不支持使用if else或者if elif这样的多重判断,用法如下: if (条件匹配) { action }

使用正则表达式对变量进行匹配,匹配成功时if指令认为条件为true,否则认为false。

[root@nginx ~]# vim /usr/local/nginx/conf.d/xiaofeifei.conf
....
    location /test2 {
    if ( !-e $request_filename ){
        echo "$request_filename is not exist";
        }
    }
....
[root@nginx ~]# nginx -s reload    #注意复制有时也不靠谱,仔细检测。
测试:[root@nginx ~]# curl var.timinglee.org/test2/index.html
/data/web/html/test2/index.html is not exist
[root@nginx ~]# mkdir -p /data/web/html/test2   #如果这个文件存在,就直接显示文件内容
[root@nginx ~]# echo test2 - 172.25.254.100 > /data/web/html/test2/index.html
[root@nginx ~]# curl var.timinglee.org/test2/index.html
test2 - 172.25.254.100
2.ngx_http_rewrite_module 模块指令:break指令

用于中断当前相同作用域(location)中的其他Nginx配置;与该指令处于同一作用域的Nginx配置中,位于它前面的配置生效; 位于后面的 ngx_http_rewrite_module 模块中指令就不再执行 Nginx服务器在根据配置处理请求的过程中遇到该指令的时候,回到上一层作用域继续向下读取配置,、 该指令可以在server块和locationif块中使用。

注意: 如果break指令在location块中后续指令还会继续执行,只是不执行 ngx_http_rewrite_module 模块的指令,其它指令还会执行。

[root@nginx ~]# vim /usr/local/nginx/conf.d/xiaofeifei.conf
....
location /break {
	default_type text/html;
	set $name lee;
	echo $name;
	if ( $http_user_agent = "curl/7.76.1" ){
		break;
		}
	set $id 666;
	echo $id;
	}
    .....
[root@nginx ~]# nginx -s reload
测试:
[root@nginx ~]# curl  var.timinglee.org/break
lee

[root@nginx ~]# curl -A "firefox"  var.timinglee.org/break
lee
666
3.ngx_http_rewrite_module 模块指令:return指令

return用于完成对请求的处理,并直接向客户端返回响应状态码,比如:可以指定重定向URL(对于特殊重 定向状态码,301/302等) 或者是指定提示文本内容(对于特殊状态码403/500等),处于此指令后的所有配 置都将不被执行,return可以在server、if 和 location块进行配置。

[root@nginx ~]# vim /usr/local/nginx/conf.d/xiaofeifei.conf
....
location /return {
	default_type text/html;
	if ( !-e $request_filename){
		return 301 http://www.baidu.com;
		}
		echo "$request_filename is exist";
	}
....
[root@nginx ~]# nginx -s reloaad
测试:
[root@nginx ~]# curl -I var.timinglee.org/return
HTTP/1.1 301 Moved Permanently
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 13:02:52 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Keep-Alive: timeout=60
Location: http://www.baidu.com
[root@nginx ~]# mkdir -p /data/web/html/return
[root@nginx ~]# curl -I var.timinglee.org/return  #如果存在if就不生效,检测动作。
HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 13:03:50 GMT
Content-Type: text/html
Connection: keep-alive
Keep-Alive: timeout=60
4.ngx_http_rewrite_module 模块指令:set 指令

指定key并给其定义一个变量,变量可以调用Nginx内置变量赋值给key 另外set定义格式为set $key value,value可以是text, variables和两者的组合。

可以看自定义变量的地方。

5.rewrite 指令:域名永久与临时重定向

1.域名的临时的调整,后期可能会变,之前的域名或者URL可能还用、或者跳转的目的域名和URL还会跳 转,这种情况浏览器不会缓存跳转,临时重定向不会缓存域名解析记录(A记录),但是永久重定向会缓存。

2.永久重定向301:域名永久型调整,即域名永远跳转至另外一个新的域名,之前的域名再也不使用,跳转记录可以缓存到 客户端浏览器 ;永久重定向会缓存DNS解析记录, 浏览器中有 from disk cache 信息,即使nginx服务器无法访问,浏览器也 会利用缓存进行重定向。

3.临时重定向302:域名临时重定向,告诉浏览器域名不是固定重定向到当前目标域名,后期可能随时会更改,因此浏览器 不会缓存当前域名的解析记录,而浏览器会缓存永久重定向的DNS解析记录,这也是临时重定向与永久 重定向最大的本质区别。 即当nginx服务器无法访问时,浏览器不能利用缓存,而导致重定向失败。

4.redirect:临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URL给客户端 ;由客户端重新发起请求;使用相对路径,或者http://或https://开头,状态码:302 。

5.permanent;重写完成后以永久重定向方式直接返回重写后生成的新URL给客户端 ;由客户端重新发起请求,状态码:301。

[root@nginx ~]# mkdir /data/web/var -p
[root@nginx ~]# echo var page - 172.25.254.100 > /data/web/var/index.html
[root@nginx ~]# vim /usr/local/nginx/conf.d/xiaofeifei.conf
server {
	listen 80;
	server_name var.timinglee.org;
	root /data/web/html;
	index index.html;
	location / {
		root /data/web/var;
		index index.html;
		rewrite / http://nginx.timinglee.org permanent;  
		rewrite / http://nginx.timinglee.org redirect;
	}
}
[root@nginx ~]# nginx -s reload 
#先全部注释掉,在访问var.timinglee.org,测试 nginx.timinglee.org对不对。
#[root@nginx ~]# curl nginx.timinglee.org    nginx.timinglee.org - 172.25.254.100
#[root@nginx ~]# curl var.timinglee.org      var page - 172.25.254.100
测试:#测试的时候一个一个打开,依次一个。
[root@nginx ~]# curl -I var.timinglee.org   #permanent301永久
HTTP/1.1 301 Moved Permanently
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 13:15:11 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Keep-Alive: timeout=60
Location: http://nginx.timinglee.org
[root@nginx ~]# curl -I var.timinglee.org   #redirect302临时
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 13:16:17 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Keep-Alive: timeout=60
Location: http://nginx.timinglee.org
6.rewrite 指令:break 与 last

1.break:重写完成后,停止对当前URL在当前location中后续的其它重写操作;而后直接跳转至重写规则配置块之后的其它配置,结束循环,建议在location中使用;适用于一个URL一次重写。

2.last:重写完成后,停止对当前URI在当前location中后续的其它重写操作;而后对新的URL启动新一轮重写检查,不建议在location中使用;适用于一个URL多次重写,要注意避免出现超过十次以及URL重写后返回错误的给用户。

[root@nginx ~]# mkdir -p /data/web/html/{test1,test2,break,last}
[root@nginx ~]# echo test1 - 172.25.254.100 > /data/web/html/test1/index.html
[root@nginx ~]# echo test2 - 172.25.254.100 > /data/web/html/test2/index.html
[root@nginx ~]# echo break - 172.25.254.100 > /data/web/html/break/index.html
[root@nginx ~]# echo last - 172.25.254.100 > /data/web/html/last/index.html
[root@nginx ~]# vim /usr/local/nginx/conf.d/xiaofeifei.conf
.....
location /break {
	rewrite ^/break/(.*) /test1/$1;   #访问break找test1,再找到test2,主要是看效果。
	rewrite ^/test1/(.*) /test2/$1;
}
location /last {
        root /data/web/html;
        rewrite ^/last/(.*) /test1/$1;
        rewrite ^/test1/(.*) /test2/$1;
}
location /test1 {
	default_type text/html;
	echo "timinglee test1 hahahahahahahahahahaahahahhahahaa";
}
location /test2 {
	root /data/web/html;
}
....
[root@nginx ~]# nginx -s reload
测试:
[root@nginx ~]# curl var.timinglee.org/break/
test2 - 172.25.254.100
[root@nginx ~]# curl var.timinglee.org/test1/
timinglee test1 hahahahahahahahahahaahahahhahahaa
[root@nginx ~]# curl var.timinglee.org/test2/
test2 - 172.25.254.100
[root@nginx ~]# curl var.timinglee.org/last/
test2 - 172.25.254.100
或者
[root@nginx ~]# vim /usr/local/nginx/conf.d/xiaofeifei.conf
....
location /break {
	root /data/web;
	rewrite ^/break/(.*) /test1/$1 break;    #直接停止
	rewrite ^/test1/(.*) /test2/$1;
}
....
[root@nginx ~]# curl var.timinglee.org/break/index.html
test1 - 172.25.254.100
[root@nginx ~]# vim /usr/local/nginx/conf.d/xiaofeifei.conf
....
location /last {
        root /data/web/html;
        rewrite ^/last/(.*) /test1/$1 last;   #跳出来找test1
        rewrite ^/test1/(.*) /test2/$1;
....
[root@nginx ~]# curl var.timinglee.org/last/index.html
timinglee test1 hahahahahahahahahahaahahahhahahaa
7.rewrite 指令:自动跳转 https

在不影响用户请求的情况下将http请求全 部自动跳转至 https,另外也可以实现部分 location 跳转

[root@nginx ~]# cd /usr/local/nginx/
[root@nginx ~]# mkdir -p certs
[root@nginx ~]# openssl req  -newkey  rsa:2048 -nodes -sha256 -keyout /usr/local/nginx/certs/timinglee.org.key -x509 -days 365 -out /usr/local/nginx/certs/timinglee.org.crt
#CN;Shaanxi;Xi'an;timinglee;刘大帅;nginx.timinglee.org;admin@timinglee.org
[root@Nginx ~]# vim /usr/local/nginx/conf.d/xiaozhuzhu.conf
server {
    listen 80;
    listen 443 ssl;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;
    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 ){
            rewrite / https://$host redirect;
        }
    }
}
测试:#也可以在浏览器访问。
[root@nginx ~]# curl -L www.timinglee.org
curl: (60) SSL certificate problem: self-signed certificate
More details here: https://curl.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.
[root@nginx ~]# curl -I www.timinglee.org
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 14:02:16 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Keep-Alive: timeout=60
Location: https://www.timinglee.org
8.rewrite 指令:判断文件是否存在

当用户访问到网站的时输入了一个错误的URL,可以将用户重定向至官网首页

[root@Nginx ~]# vim /usr/local/nginx/conf.d/xiaozhuzhu.conf
server {
    listen 80;
    listen 443 ssl;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;
    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 ){
            rewrite /(.*) https://$host/$1 redirect;
        }

        if ( !-e $request_filename ){
            rewrite /(.*) https://$host/index.html redirect;
        }
    }
}
nginx -s reload
测试:浏览器访问https://www.timinglee.org/a/b/文件不存在会自动跳转。建议还是浏览器看效果好点。
[root@nginx html]# curl -k https://www.timinglee.org
nginx.timinglee.org - 172.25.254.100
[root@nginx ~]# cd /data/web/html/
[root@nginx html]# ls
break  images  index.html  last  return  test1  test2
[root@nginx html]# curl -k https://www.timinglee.org/test1/   #存在的文件访问他原本的内容
test1 - 172.25.254.100
9.Nginx 防盗链

防盗链基于客户端携带的referer实现,referer是记录打开一个页面之前记录是从哪个页面跳转过来的标 记信息,如果别人只链接了自己网站图片或某个单独的资源,而不是打开了网站的整个页面,这就是盗链。在一个web 站点盗链另一个站点的资源信息,比如:图片、视频等。

[root@node2 ~]# mkdir -p /data/web/html/images   #自己拖入图片,两张图片不能再一起
测试:在浏览器访问www.timinglee.org/images/2.jpg,看有没有图片显示。1.jpg放在/data/web/html/里面。
#盗链网页
#新建一个主机172.25.254.20,盗取另一台主机www.timinglee.org/images/2.jpg的图片
[root@node2 ~]# yum install httpd -y
[root@node2 ~]# vim /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/2.jpg" >
    <h1 style="color:red">一身清贫怎敢入繁华,两袖清风怎敢误佳人</h1>
    <p><a href=http://www.timinglee.org>刘大帅</a>陌上人如玉,公子世无双</p>
  </body>

</html>

#重启apache并访问http://172.25.254.20 
测试:验证是否会在被盗连的web站点的日志中出现以下盗链日志信息
[root@Nginx ~]# cat /usr/local/nginx/logs/access.log
172.25.254.1 - - [18/Aug/2024:22:27:10 +0800] "GET /images/2.jpg HTTP/1.1" 200 47497 "https://www.baidu.com/s?wd=www.timinglee.org%2Fimages%2F2.jpg&rsv_spt=1&rsv_iqid=0xe64f2cdd00140512&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&tn=68018901_16_pg&rsv_enter=1&rsv_dl=ib&rsv_sug3=2&rsv_n=2" "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"
[root@Nginx ~]# vim /usr/local/nginx/conf.d/xiaozhuzhu.conf
server {
	listen 80;
	listen 443 ssl;
	server_name nginx.timinglee.org;
	root /data/nginx/html/https;
	index index.html;
	ssl_certificate /usr/local/nginx/certs/timinglee.org.crt;
	ssl_certificate_key /usr/local/nginx/certs/timinglee.org.key;
	ssl_session_cache shared:sslcache:1m;
	ssl_session_timeout 5m;
	#全局锁定
    #location / {
    #   valid_referers none blocked server_names *.timinglee.org ~/.baidu/.;
    #   if ( $invalid_referer ){
    #            return 404;
    ##    }
    #}                         #在开启防盗链的时候需要注释掉全局。
	#防盗链
	location /images {
	valid_referers none blocked server_names *.timinglee.org ~\.baidu\.;
	if ( $invalid_referer ){
		rewrite ^/ http://www.timinglee.org/1.jpg permanent;
		}
	}
}
[root@nginx ~]# nginx -s reload
测试:浏览器访问172.25.254.20                  #如果有报错的可以清除一下浏览器的缓存。

 以下是访问图片:

 有时候浏览器访问之后都有缓存,效果大大减低,可以清除缓存。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值