LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

高性能WEB服务器Nginx常用功能(四):favicon图标配置、实现Https、配置防盗链、Rewrite

admin
2025年6月29日 18:39 本文热度 100

3 Nginx 常用功能

3.15 favicon 图标配置

favicon.ico 文件是浏览器收藏网址时显示的图标,当客户端使用浏览器问页面时,浏览器会自己主动发起请求获取页面的 favicon.ico文件,但是当浏览器请求的favicon.ico文件不存在时,服务器会记录404日志,而且浏览器也会显示404报错

[root@ubuntu ~]# tail /var/log/nginx/access.log | grep favicon10.0.0.1 - - [01/Feb/2025:11:43:43 +0800"GET /favicon.ico HTTP/1.1" 404 181"http://www.m99-josedu.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36Edg/121.0.0.0"10.0.0.1 - - [01/Feb/2025:11:43:43 +0800"GET /favicon.ico HTTP/1.1" 404 181"http://www.m99-josedu.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36Edg/121.0.0.0"
#解决办法 服务器不记录访问日志server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location = /favicon.ico {        log_not_found off;        access_log off;    }
#解决办法 给出文件,并设置有效期server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location = /favicon.ico {        root /var/www/html/www.m99-josedu.com/static;        expires 7d#首次请求缓存后,7天内不再发起请求,但服务端更新后客户端有可能要7天后才更新        access_log off;    }}

3.16 Nginx 实现 Https

Nginx 中的 Https 功能需要 ngx_http_ssl_module 模块支持,使用 Yum/apt 安装的 Nginx 中已经包含了该模块的功能,如果使用的是自行通过源码编译安装的 Nginx,需要在编译的时候指定相关编译项

https://nginx.org/en/docs/http/ngx_http_ssl_module.html
ssl on|off#是否启用SSL,1.15版本中被弃用,1.25.1版本中被删除,后续不使用此参数ssl_buffer_size size; #Nginx在读取和写入SSL/TLS握手数据时使用的缓冲区大小,无关数据发送,默认值 16k                      #作用域 http, serverssl_certificate file; #当前虚拟主机的证书文件,通常是PEM格式                      #该文件中有两部份,分别是虚拟主机的证书和CA机构的证书,作用域 http, serverssl_certificate_key file; #当前虚拟主机的私钥文件路径,作用域 http, serverssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2] [TLSv1.3];                      #当前支持的SSL协议版本,默认值 TLSv1 TLSv1.1 TLSv1.2 TLSv1.3                      #作用域 http, serverssl_session_cache off|none|[builtin[:size]] [shared:name:size];                      #配置SSL缓存,作用域 http, server                      #off 禁用SSL/TLS会话缓存                      #none 通知客户端可以重用会话,但并没有缓存相关数据,默认值                      #builtin[:size] 使用OpenSSL内建缓存,可指定大小,每个 worker 进程独享                      #[shared:name:size] 使用共享缓存,每个worker进程共享该缓存中的数据,可指定name和大小ssl_session_timeout time; #配置SSL/TLS会话缓存的超时时间,默认值 5m,作用域 http, server#使用SSL/TLS会话缓存有助于减少服务器的加密和解密负担,提高HTTPS连接的响应速度,启用缓存需要 ssl_session_cache,ssl_session_timeout 两个选项一起使用
#SSL/TLS会话缓存存储的是SSL/TLS握手过程中生成的会话数据。在SSL/TLS握手过程中,服务器和客户端会交换一系列数据,其中包括协商的密钥、加密算法、会话标识符等信息。这些信息用于确保安全通信,并在建立连接后用于加密和解密通信的数据#SSL/TLS会话缓存中存储的主要数据包括 会话标识符(Session Identifier),主密钥(Master Secret),加密算法和参数#通过存储这些会话数据,SSL/TLS会话缓存允许服务器在处理新连接时,如果客户端提供了先前使用过的会话标识符,就可以重用这些数据,避免重新执行完整的SSL/TLS握手。这样可以大幅度减少握手过程中的计算和通信开销,提高性能和响应速度。同时,它还有助于减少服务器的负担,因为不需要重新生成新的密钥和协商参数
#安装软件[root@ubuntu ~]# apt install easy-rsa -y[root@ubuntu ~]# cd /usr/share/easy-rsa/
#初始化证书目录[root@ubuntu easy-rsa]# ./easyrsa init-pkiinit-pki complete; you may now create a CA or requests.Your newly created PKI dir is: /usr/share/easy-rsa/pki[root@ubuntu easy-rsa]# tree pki/pki/├── openssl-easyrsa.cnf├── private├── reqs└── safessl-easyrsa.cnf2 directories, 2 files
#生成CA机构证书,不使用密码[root@ubuntu easy-rsa]# ./easyrsa build-ca nopassUsing SSL: openssl OpenSSL 3.0.2 15 Mar 2022 (Library: OpenSSL 3.0.2 15 Mar 2022)............Common Name (eg: your user, host, or server name) [Easy-RSA CA]:josedu.comCA creation complete and you may now import and sign cert requests.Your new CA certificate file for publishing is at:/usr/share/easy-rsa/pki/ca.crt
#生成私钥和证书申请文件[root@ubuntu easy-rsa]# ./easyrsa gen-req www.m99-josedu.com nopassUsing SSL: openssl OpenSSL 3.0.2 15 Mar 2022 (Library: OpenSSL 3.0.2 15 Mar 2022)............Common Name (eg: your user, host, or server name) [www.m99-josedu.com]:Keypair and certificate request completed. Your files are:req: /usr/share/easy-rsa/pki/reqs/www.m99-josedu.com.reqkey: /usr/share/easy-rsa/pki/private/www.m99-josedu.com.key
#签发证书[root@ubuntu easy-rsa]# ./easyrsa sign-req server www.m99-josedu.comUsing SSL: openssl OpenSSL 3.0.2 15 Mar 2022 (Library: OpenSSL 3.0.2 15 Mar 2022)............Certificate created at: /usr/share/easy-rsa/pki/issued/www.m99-josedu.com.crt
#合并服务器证书,签发机构证书为一个文件,注意顺序[root@ubuntu easy-rsa]# cat pki/issued/www.m99-josedu.com.crt pki/ca.crt > pki/www.m99-josedu.com.pem
#给私钥加读权限[root@ubuntu easy-rsa]# chmod +r pki/private/www.m99-josedu.com.key
#查看[root@ubuntu easy-rsa]# tree pkipki├── ca.crt #CA机构证书............├── issued│   └── www.m99-josedu.com.crt #虚拟主机服务器证书├── openssl-easyrsa.cnf├── private│   ├── ca.key #CA机构私钥│   └── www.m99-josedu.com.key #虚拟主机服务器私钥............├── reqs│   └── www.m99-josedu.com.req #证书申请文件............└── www.m99-josedu.com.pem #合并后的pem文件
#配置httpsserver {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;}
server {    listen 443 ssl;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    ssl_certificate /usr/share/easy-rsa/pki/www.m99-josedu.com.pem;    ssl_certificate_key /usr/share/easy-rsa/pki/private/www.m99-josedu.com.key;    ssl_session_cache shared:sslcache:20m;    ssl_session_timeout 10m;
#在浏览器中测试,如果浏览器提示不安全,则导入CA证书后再次重启浏览器
#配置http 强制跳转 httpsserver {    listen 80;    server_name www.m99-josedu.com;    return 301 https://$host$request_uri#301重定向    rewrite ^(.*) https://$server_name$1 permanent#rewrite 重定向,二选一
#在浏览器中测试 http://www.m99-josedu.com/index.html?abc=123&def=456
#http 和 https 写在同一个配置中server {    listen 80;    listen 443 ssl;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    ssl_certificate /usr/share/easy-rsa/pki/www.m99-josedu.com.pem;    ssl_certificate_key /usr/share/easy-rsa/pki/private/www.m99-josedu.com.key;    ssl_session_cache shared:sslcache:20m;    ssl_session_timeout 10m;}
#同一个配置中自动跳转server {    listen 80;    listen 443 ssl;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    ssl_certificate /usr/share/easy-rsa/pki/www.m99-josedu.com.pem;    ssl_certificate_key /usr/share/easy-rsa/pki/private/www.m99-josedu.com.key;    ssl_session_cache shared:sslcache:20m;    ssl_session_timeout 10m;    if ($scheme = http) {        return 301 https://$host$request_uri;        rewrite ^(.*) https://$server_name$1 permanent#二选一    }}

3.17 Nginx 中配置防盗链

盗链是指某站点未经允许引用其它站点上的资源,基于访问安全考虑,Nginx 支持通过 ngx_http_referer_module 模块,检查和过滤 Referer 字段的值,来达到防盗链的效果

HTTP Referer是Header的一部分,当浏览器向Web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器借此可以获得一些信息用于处理,例如校验加载图片、文件等来源是否是指定域名,如不是则禁止访问。因此HTTP Referer头信息是可以通过程序来伪装生成的,所以通过Referer信息防盗链并非100%可靠,但是,它能够限制大部分的盗链情况

https://nginx.org/en/docs/http/ngx_http_referer_module.html
valid_referers none |blocked|server_names|string ...;# Nginx 会使用请求头中的 referer 字段值和 valid_referers 指定的规则进行对比,如果不匹配,会将 $invalid_referer 变量的值设为 1,默认该变量值为空字符串,作用域 server, location# none 如果请求头中没有 referer 字段,则 $invalid_referer 变量值为空# blocked 如果请求头中有 referer 字段,但其值不合法(不是以 http 或 https 开头),则 $invalid_referer 变量为空# server_names 具体主机名,可以写一个或多个,支持正则和通配符,如果请求头中的 referer 字段值与定义的 server_names 匹配,则$invalid_referer 变量为空
盗链演示
server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;}
server {    listen 80;    server_name www.abc-123.com;    root /var/www/html/www.abc-123.com;}
[root@ubuntu ~]# cat /var/www/html/www.m99-josedu.com/test.htmlhello world<img src="http://www.abc-123.com/test.jpg" />
#当访问者在浏览器中打开 http://www.m99-josedu.com/test.html 时,该页面会引用一个 http://www.abc-123.com 站点的资源#对于http://www.abc-123.com 站点而言,其资源就是被资链了
利用 valid_referers 指令实现防盗链
#对于 http://www.abc-123.com/test.jpg 而言,此次请求是从 http://www.m99-magedu.com 来的 #则只需要根据 referer 字段值禁用未经允许的访问即可server {    listen 80;    server_name www.abc-123.com;    root /var/www/html/www.abc-123.com;    valid_referers none blocked server_names *.test.com ~\.baidu\. ~\.bing\. ~\.so\.;    if ($invalid_referer) { # if 指令后面要有空格, 如果不是上述referer,就返回403        return 403 "Forbidden Access";    }}
无法再盗用资源
#access log 中返回 403[root@ubuntu ~]# tail -1 /var/log/nginx/access.log10.0.0.1 - - [05/Feb/2025:08:32:42 +0800"GET /test.jpg HTTP/1.1" 403 16"http://www.m99-josedu.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36Edg/121.0.0.0"
#在浏览器中直接访问 http://www.abc-123.com/test.jpg 可以打开,查看 access log,返回 200, referer 为空[root@ubuntu ~]# tail -2 /var/log/nginx/access.log10.0.0.1 - - [05/Feb/2025:08:34:28 +0800"GET /test.jpg HTTP/1.1" 200 11647 "-""Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0"
#referer 为空,可以访问[root@ubuntu ~]# curl http://www.abc-123.com/index.htmlhello world
#referer 不合法,也可以访问[root@ubuntu ~]# curl -"test" http://www.abc-123.com/index.htmlhello world
#允许访问的 referer[root@ubuntu ~]# curl -"http://www.test.com" http://www.abc-123.com/index.htmlhello world
#允许访问的 referer[root@ubuntu ~]# curl -"http://www.baidu.com/abc" http://www.abc-123.com/index.htmlhello world
#不允许访问的 referer[root@ubuntu ~]# curl -"http://www.xyz.com" http://www.abc-123.com/index.htmlForbidden Access

3.18 Nginx 中的 Rewrite

在 Nginx 中,rewrite 指令用于重写 URI,允许 Nginx 修改客户端请求的 URI,基于此,可用该指令实现 URL 重定向,修改请求参数,改变请求含义,改变 URL 结构等,该指令来自于 ngx_http_rewrite_module 模块

ngx_http_rewrite_module 模块是 Nginx 中的一个核心模块,不管是 yum/apt 安装还是编译安装,默认都己经包含在 Nginx 中了,它提供了强大的 URL 重写和重定向功能。主要作用是允许管理员通过配置文件来修改客户端请求的 URI,从而实现重写 URL、重定向请求、更改请求参数等操作

https://nginx.org/en/docs/http/ngx_http_rewrite_module.html
3.18.1 相关指令说明
break#中断当前相同作用域(location)中的其它 ngx_http_rewrite_module 模块的配置和指令,返回到上一作用域继续执行       #该指令后的其它指令和配置还会执行,只中断 ngx_http_rewrite_module 指令,作用域 server, location, ifif (condition) { ... }        # 允许在配置中使用条件判断,使用正则表达式(pcre风格)对变量进行匹配,匹配成功返回true,执行后续指令        if指令仅能做单次判断,不支持 if else 多分支        if ($var){ } 这种写法,如果变量对应的值是空字符串或0,就返回false        # nginx 1.0.1之前$变量的值如果以0开头的任意字符串会返回false        # 作用域 server, location        # 支持的运算符        # = 比较变量和字符串是否相等        # != 比较变量和字符串是否不相等        # ~ 区分大小写,是否匹配正则,包含        # !~ 区分大小写,是否不匹配正则,包含        # ~* 不区分大小写,是否匹配正则,包含        # !~* 不区分大小写,是否不匹配正则,不包含        # -f|!-f 判断文件是否存在|不存在        # -d|!-d 判断目录是否存在|不存在        # -x|!-x 判断文件是否可执行|不可执行        # -e|!-e 判断文件(包括文件,目录,软链接)是否存在|不存在return code [text];return code URL;return URL; # 不写code ,默认值为302            # 直接向客户端返回状态码,字符串,或者URL,如果返回的字符串中包含空格,要加引号,如果返回URL,要写完整            # 此指令后的其它指令或配置将不再执行,作用域 server, location, ifrewrite regex replacement [flag];            # 通过正则表达式匹配来改变URI,在一个配置段中可以有一条或多条,按照顺序从上下往下匹配            # 作用域 server, location, if            # 如果有多条规则,被某一条规则命中并替换后,会用新的URI再从头开始逐一匹配,直到没有被命中为止            # 但是重复匹配次数不能超过 10次,否则会报500            # regex PCRE 风格的正则表达式,表示要查找的内容            # replacement 用于替换的字符串            # [flag] 标志位,用于控制 rewrite 指令的行为last|break|redirect|permanent            # last 如果被当前 rewrite 规则匹配上,替换后结束本轮替换,开始下一轮替换            # break 如果被当前 rewrite 规则匹配上,替换后结束当前代码段的重写替换,后续所有 rewrite 都不执行            # redirect 如果被当前 rewrite 规则匹配上,替换后执行 302 临时重定向            # permanent 如果被当前 rewrite 规则匹配上,替换后执行 301 永久重定向            # last 和 break 在服务器内部实现跳转,客户端浏览器地址栏中的信息不会发生变化            # redirect 和 permanent 在客户端实现跳转,客户端浏览器地址栏中的信息会发生变化rewrite_log on|off; #是否记录 ngx_http_rewrite_module 模块产生的日志到 error_log 中,默认值 off            #如果开启,需要将 error_log 的级别设为 notice,作用域 http, server, location, ifset $variable value#设置变量,给变量赋值,作用域 server, location, if

last 和 break

相同点:

  • 无论是 break 还是 last,它们都会中止当前 location 块的处理,并跳出该块,客户端浏览器地址栏中的信息不会发生变化


不同点:

  • break:终止当前代码段中的所有 rewrite 匹配

  • last:中止当前 location 中的 rewrite 匹配,用替换后的 RUI 继续从第一条规则开始执行下一轮 rewrite


3.18.2 PCRE 风格正则表达式

PCRE(Perl Compatible Regular Expressions)风格的正则表达式在设计上兼容Perl语言的正则表达式语法,具有灵活且功能强大的特点。下面是一些 PCRE 风格正则表达式中常见的元字符和功能

#元字符
#匹配除换行符外的任意字符\w #匹配字母数字下划线中文字\s #匹配任意空白字符\d #匹配任意数字,相当于[0-9]\b #匹配单词开始或结束[] #匹配括号内的任意一个字符 [abc] 表示abc中的任意一个字符[^] #匹配除了括号内字符之外的任意一个字符 [^abc] 表示任意一个除 abc 之外的字符
#匹配内容的开始位置#匹配内容的结束位置#匹配前面的字符零次或多次#匹配前面的字符一次或多次#匹配前面的字符零次或一次{n} #匹配前面的字符n次{n,} #匹配前面的字符至少n次{n,m} #匹配前面的字符n次到m次{,m} #匹配前面的字符最多m次
#或,用于在模式中指定多个备选项() #分组,用于将多个模式组合在一起,并捕获匹配的文本 $1 $2 $n 后向引用#转义字符,用于取消元字符的特殊意义,或引入某些特殊字符

3.18.3 相关指令测试

break 指令测试

server {    listen 80;    listen 443 ssl;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location /break {        set $var1 josedu;        echo $var1;        break;        set $var2 1234; # set 是属于 ngx_http_rewrite_module 模块指令,此句在 break 之后,不生效        echo "$var1 -- $var2"; # 不输出 var2        return 200 "hello break"; # return 是属于 ngx_http_rewrite_module 模块指令,此句在 break 之后,不生效    }
#测试[root@ubuntu ~]# curl http://www.m99-josedu.com/breakjosedujosedu --
if 指令测试
server {    listen 80;    listen 443 ssl;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    ssl_certificate /usr/share/easy-rsa/pki/www.m99-josedu.com.pem;    ssl_certificate_key /usr/share/easy-rsa/pki/private/www.m99-josedu.com.key;    ssl_session_cache shared:sslcache:20m;    ssl_session_timeout 10m;
    location /scheme {        if ($scheme = http) {            return 200 "http";        }        if ($scheme = https) {            return 200 "https";        }    }
    location /test {        return 200 $scheme;    }
    location /file {        if (!-$request_filename) {            return 200 "$request_filename file not exists";        }    }}
[root@ubuntu ~]# touch /var/www/html/www.m99-josedu.com/file.txt
#测试[root@ubuntu ~]# curl http://www.m99-josedu.com/schemehttp[root@ubuntu ~]# curl htTP://www.m99-josedu.com/schemehttp[root@ubuntu ~]# curl -k htTPS://www.m99-josedu.com/schemehttps[root@ubuntu ~]# curl -k https://www.m99-josedu.com/schemehttpsroot@ubuntu ~]# curl http://www.m99-josedu.com/testhttp[root@ubuntu ~]# curl -k https://www.m99-josedu.com/testhttps[root@ubuntu ~]# curl -k https://www.m99-josedu.com/file.html/var/www/html/www.m99-josedu.com/file.html file not exists[root@ubuntu ~]# curl -k https://www.m99-josedu.com/file.log/var/www/html/www.m99-josedu.com/file.log file not exists[root@ubuntu ~]# curl -k https://www.m99-josedu.com/file.txt
set 配合 if
server {    listen 80;    listen 443 ssl;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    set $slow 1;    location =/test.img {        if ($slow) {            limit_rate 10k;        }    }
#测试[root@ubuntu ~]# wget http://www.m99-josedu.com/test.img
return 指令测试
server {    listen 80;    listen 443 ssl;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location /return {        if ($http_user_agent ~* curl|wget|ApacheBench) {            return 403 "agent error!";        }        return 200 "success";    }}
[root@ubuntu ~]# curl http://www.m99-josedu.com/returnagent error![root@ubuntu ~]# curl -I http://www.m99-josedu.com/returnHTTP/1.1 403 ForbiddenServer: nginxDate: Mon, 05 Feb 2025 06:27:39 GMTContent-Type: application/octet-streamContent-Length: 12Connection: keep-alive
#指定 agent[root@ubuntu ~]# curl -A "chrome" http://www.m99-josedu.com/returnsuccess[root@ubuntu ~]# curl -IA "chrome" http://www.m99-josedu.com/returnHTTP/1.1 200 OKServer: nginxDate: Mon, 05 Feb 2025 06:29:31 GMTContent-Type: application/octet-streamContent-Length: 7Connection: keep-alive
return 指令测试
server {    listen 80;    listen 443 ssl;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location = /return_url {        return http://www.baidu.com;    }
#测试[root@ubuntu ~]# curl http://www.m99-josedu.com/return_url<html><head><title>302 Found</title></head><body><center><h1>302 Found</h1></center><hr><center>nginx</center></body></html>
[root@ubuntu ~]# curl -I http://www.m99-josedu.com/return_urlHTTP/1.1 302 Moved TemporarilyServer: nginxDate: Mon, 05 Feb 2025 06:38:21 GMTContent-Type: text/htmlContent-Length: 138Connection: keep-aliveLocation: http://www.baidu.com
#加选项跟踪跳转,能访问到 www.baidu.com[root@ubuntu ~]# curl -IL http://www.m99-josedu.com/return_urlHTTP/1.1 302 Moved TemporarilyServer: nginxDate: Mon, 05 Feb 2025 06:42:43 GMTContent-Type: text/htmlContent-Length: 138Connection: keep-aliveLocation: http://www.baidu.com
HTTP/1.1 200 OKAccept-Ranges: bytesCache-Control: private, no-cache, no-store, proxy-revalidate, no-transformConnection: keep-aliveContent-Length: 277Content-Type: text/htmlDate: Mon, 05 Feb 2025 06:42:43 GMTEtag: "575e1f59-115"Last-Modified: Mon, 13 Jun 2021 02:50:01 GMTPragma: no-cacheServer: bfe/1.0.8.18
#自动跳转页面效果要在浏览器中测试
rewirte 指令测试
[root@ubuntu ~]# echo "11111" > /var/www/html/www.m99-josedu.com/1.html[root@ubuntu ~]# echo "22222" > /var/www/html/www.m99-josedu.com/2.html[root@ubuntu ~]# echo "33333" > /var/www/html/www.m99-josedu.com/3.html[root@ubuntu ~]# echo "aaaaa" > /var/www/html/www.m99-josedu.com/a.html[root@ubuntu ~]# echo "bbbbb" > /var/www/html/www.m99-josedu.com/b.html[root@ubuntu ~]# echo "ccccc" > /var/www/html/www.m99-josedu.com/c.html
server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location / {        rewrite /1.html /2.html;        rewrite /2.html /3.html;    }
    location /2.html {        rewrite /2.html /a.html;    }
    location /3.html {        rewrite /3.html /b.html;    }}
1.html ----> 2.thml2.html ----> 3.html3.html ----> b.html
[root@ubuntu ~]# curl http://www.m99-josedu.com/1.htmlbbbbb
server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location / {        rewrite /1.html /2.html;        rewrite /2.html /3.html;        rewrite /b.html /c.html;    }
    location /2.html {        rewrite /2.html /a.html;    }
    location /3.html {        rewrite /3.html /b.html;    }}
1.html ----> 2.thml2.html ----> 3.html3.html ----> b.html# b.html ----> c.html[root@ubuntu ~]# curl http://www.m99-josedu.com/1.htmlccccc
rewirte 指令测试 - 配合 break
server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location / {        rewrite /1.html /2.html break;        rewrite /2.html /3.html;    }
    location /2.html {        rewrite /2.html /a.html;    }
    location /3.html {        rewrite /3.html /b.html;    }}
1.html ----> 2.thmlbreak 结束当前 server 配置段中的所有 rewrite[root@ubuntu ~]# curl http://www.m99-josedu.com/1.html22222
rewirte 指令测试 - 配合 last
server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location / {        rewrite /1.html /2.html last;        rewrite /2.html /3.html;    }
    location /2.html {        rewrite /2.html /a.html;    }
    location /3.html {        rewrite /3.html /b.html;    }}
1.html ----> 2.thml last 结束当前 location 中的本轮 rewrite,继续执行下一轮 rewrite2.html ----> a.thml 一下轮 location /2.html 的优先级更高[root@ubuntu ~]# curl http://www.m99-josedu.com/1.htmlaaaaa
server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location / {      rewrite /1.html /22.html last;      rewrite /2.html /3.html;    }
    location /2.html {        rewrite /2.html /a.html;    }
    location /3.html {        rewrite /3.html /b.html;    }}
[root@ubuntu ~]# echo "22-22" > /var/www/html/www.m99-josedu.com/22.html1.html ----> 22.thml last 结束当前 location 中的本轮 rewrite,继续执行下一轮 rewrite# 后续没有 22.html 的规则,返回 22.html[root@ubuntu ~]# curl http://www.m99-josedu.com/1.html22-22
server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location / {        rewrite /1.html /2.html last;        rewrite /2.html /3.html;    }
    location /2.html {        rewrite /2.html /1.html;    }
    location /3.html {        rewrite /3.html /b.html;    }}
1.html ----> 2.thml last2.html ----> 1.thml1.html ----> 2.thml last... 无限循环,最终返回 500 服务器内部错误
[root@ubuntu ~]# curl http://www.m99-josedu.com/1.html<html><head><title>500 Internal Server Error</title></head><body><center><h1>500 Internal Server Error</h1></center><hr><center>nginx</center></body></html>[root@ubuntu ~]# tail -1 /var/log/nginx/error.log2025/02/05 17:24:05 [error] 3477#3477*1 rewrite or internal redirection cyclewhile processing "/2.html", client: 127.0.0.1, server: www.m99-josedu.com,request: "HEAD /1.html HTTP/1.1", host: "www.m99-josedu.com"
rewirte 指令测试 - 配合 redirect
server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location / {        rewrite /1.html /2.html redirect;        rewrite /2.html /3.html;    }
    location /2.html {        rewrite /2.html /1.html;    }
    location /3.html {        rewrite /3.html /b.html;    }}
[root@ubuntu ~]# curl http://www.m99-josedu.com/1.html<html><head><title>302 Found</title></head><body><center><h1>302 Found</h1></center><hr><center>nginx</center></body></html>
# 1.html ----> 2.thml redirect 返回客户端让客户端去请求 2.html# 2.html ----> 1.thml 客户端请求 2.html 被 rewrite 1.html# 1.html ----> 2.thml redirect 返回客户端让客户端去请求 2.html# ... 无限循环
[root@ubuntu ~]# curl -L http://www.m99-josedu.com/1.htmlcurl: (47) Maximum (50) redirects followed#用浏览器访问 http://www.m99-josedu.com/1.html 最后地址栏会变成 http://www.m99-josedu.com/2.html#提示 重定向次数过多server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location / {        rewrite /1.html /2.html redirect;        rewrite /2.html /3.html;    }
    location /2.html {        rewrite /2.html /a.html;    }
    location /3.html {        rewrite /3.html /b.html;    }}
[root@ubuntu ~]# curl -L http://www.m99-josedu.com/1.htmlaaaaa# 1.html ----> 2.thml redirect 返回客户端让客户端去请求 2.html,这一步是客户端重定向# 2.html ----> a.thml 客户端请求 2.html 被 rewrite a.html,最终返回 a.html的内容,这一步是服务端重定向
[root@ubuntu ~]# curl -IL http://www.m99-josedu.com/1.htmlHTTP/1.1 302 Moved TemporarilyServer: nginxDate: Tue, 06 Feb 2025 02:12:10 GMTContent-Type: text/htmlContent-Length: 138Location: http://www.m99-josedu.com/2.htmlConnection: keep-aliveHTTP/1.1 200 OKServer: nginxDate: Tue, 06 Feb 2025 02:12:10 GMTContent-Type: text/html; charset=utf8Content-Length: 6Last-Modified: Mon, 05 Feb 2025 08:26:15 GMTConnection: keep-aliveETag: "65c09ba7-6"Accept-Ranges: bytes
# 浏览器访问 http://www.m99-josedu.com/1.html 地址栏中最后是 http://www.m99-josedu.com/2.html# 显示的内容是 a.html 的内容server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location / {        rewrite /1.html /2.html redirect;        rewrite /2.html /3.html;    }
    location /2.html {        rewrite /2.html /a.html redirect;    }
    location /3.html {        rewrite /3.html /b.html;    }}
[root@ubuntu ~]# curl -L http://www.m99-josedu.com/1.htmlaaaaa# 1.html ----> 2.thml redirect 返回客户端让客户端去请求 2.html,这一步是客户端重定向# 2.html ----> a.thml redirect 返回客户端让客户端去请求 2.html,这一步是客户端重定向,最终客户端访问的是 a.html
[root@ubuntu ~]# curl -IL http://www.m99-josedu.com/1.htmlHTTP/1.1 302 Moved TemporarilyServer: nginxDate: Tue, 06 Feb 2025 02:25:42 GMTContent-Type: text/htmlContent-Length: 138Location: http://www.m99-josedu.com/2.htmlConnection: keep-aliveHTTP/1.1 302 Moved TemporarilyServer: nginx
Date: Tue, 06 Feb 2025 02:25:42 GMTContent-Type: text/htmlContent-Length: 138Location: http://www.m99-josedu.com/a.htmlConnection: keep-aliveHTTP/1.1 200 OKServer: nginxDate: Tue, 06 Feb 2025 02:25:42 GMTContent-Type: text/html; charset=utf8Content-Length: 6Last-Modified: Mon, 05 Feb 2025 08:26:15 GMTConnection: keep-aliveETag: "65c09ba7-6"Accept-Ranges: bytes
# 浏览器访问 http://www.m99-josedu.com/1.html 地址栏中最后是 http://www.m99-josedu.com/a.html# 显示的内容是 a.html 的内容
rewirte 指令测试 - 配合 permanent
server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    location / {        rewrite /1.html /2.html permanent;        rewrite /2.html /3.html;    }
    location /2.html {        rewrite /2.html /a.html permanent;    }
    location /3.html {        rewrite /3.html /b.html;    }}
[root@ubuntu ~]# curl -L http://www.m99-josedu.com/1.htmlaaaaa
#除了状态码不一样之外,redirect 和 permanent 在流程上没有本质区别[root@ubuntu ~]# curl -IL http://www.m99-josedu.com/1.htmlHTTP/1.1 301 Moved PermanentlyServer: nginxDate: Tue, 06 Feb 2025 02:38:50 GMTContent-Type: text/htmlContent-Length: 162Location: http://www.m99-josedu.com/2.htmlConnection: keep-alive
HTTP/1.1 301 Moved PermanentlyServer: nginxDate: Tue, 06 Feb 2025 02:38:50 GMTContent-Type: text/htmlContent-Length: 162Location: http://www.m99-josedu.com/a.htmlConnection: keep-alive
HTTP/1.1 200 OKServer: nginxDate: Tue, 06 Feb 2025 02:38:50 GMTContent-Type: text/html; charset=utf8Content-Length: 6Last-Modified: Mon, 05 Feb 2025 08:26:15 GMTConnection: keep-aliveETag: "65c09ba7-6"Accept-Ranges: bytes
#但是在浏览器中,会缓存此次重定向的流程,在得到最终结果之前,不会访问服务器,通过开发者工具可以看到 disk cache 相关提示
3.18.4 相关案例
#访问不存在的资源,跳转到首页server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    if (!-e $request_filename) {        rewrite .* /index.html redirect;        return 302 http://$host#二选一    }}
#根据不同的设备适配不同的项目server {    listen 80;    server_name www.m99-josedu.com;    root /var/www/html/www.m99-josedu.com;    if ($http_user_agent ~* "android|iphone|ipad") {        rewrite ^(.*)$ http://m.m99-josedu.com/$1 redirect#用 return 指令也可以    }}
#网站维护,只有特定客户端IP能访问,其它客户端重定向到提示页面server {    listen 80;    server_name www.m99-magedu.com;    root /var/www/html/www.m99-magedu.com;    if ($remote_addr != "10.0.0.1") {        rewrite ^(.*)$ /msg.html break;    }}

— END —


阅读原文:原文链接


该文章在 2025/7/1 23:01:01 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved