nginx测试rewrite

博客围绕Nginx展开,介绍了Nginx测试rewrite时last、break、redirect、permanent的作用,还提及wget查看、多种域名跳转等内容,包括根据浏览器agent、api地址、状态码、ip等进行跳转,以及rewrite规则遇到break和last后的执行情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

nginx测试rewrite

last :相当于 Apache 里的(L)标记,表示完成rewrite 匹配;
break: 本条规则匹配完成后,终止匹配,不再匹配后面的规则。
# 其中last 和 break 用来实现 URL 重写时,浏览器地址栏URL 地址不变
redirect: 返回 302 临时重定向,浏览器地址会显示跳转后的 URL 地址。
permanent: 返回 301永久重定向,浏览器地址栏会显示跳转后的URL 地址
#不配置将显示304
[root@node1 ~]# yum -y install gcc make pcre-devel openssl-devel
[root@node1 ~]# tar xf nginx-1.22.1.tar.gz
[root@node1 ~]# cd nginx-1.22.1/
[root@node1 nginx-1.22.1]# ./configure  --prefix=/usr/local/nginx  --user=nginx  --with-http_ssl_module
[root@node1 nginx-1.22.1]#  make && make install
[root@node1 nginx-1.22.1]# useradd nginx -s /sbin/nologin
[root@node1 nginx-1.22.1]# /usr/local/nginx/sbin/nginx
[root@node1 nginx-1.22.1]# cd /usr/local/nginx/
[root@node1 nginx]# mkdir html/static
[root@node1 nginx]# echo "html/static/index.html">html/static/index.html
[root@node1 nginx]# echo "html/static/node1.html">html/static/node1.html


#访问显示
http://www.myweb.com/static/ -->  html/static/index.html
http://www.myweb.com/static/test.html -->  html/static/test.html
http://www.myweb.com/forum.php -->  404 Not Found

last :相当于 Apache 里的L)标记,表示完成rewrite 匹配;

break: 本条规则匹配完成后,终止匹配,不再匹配后面的规则。

redirect: 返回 302 临时重定向,浏览器地址会显示跳转后的URL 地址。

permanent: 返回301永久重定向,浏览器地址栏会显示跳转后的 URL 地址。

其中 last 和 break 用来实现 URL 重写时,浏览器地址栏URL 地址不变。

#访问  http://www.myweb.com/forum.php  -跳转->  html/static/test.html

server {
        listen       80;
        server_name www.myweb.com;

# 本地目录重写
        # 状态码304 地址栏不变化  http://www.myweb.com/forum.php
        rewrite ^/forum.php$ /static/node1.html last;  

        # 状态码304 地址栏不变化  http://www.myweb.com/forum.php
        rewrite ^/forum.php$ /static/node1.html break;  
        
        # 状态码301 地址栏变为http://www.myweb.com/static/test.html
        rewrite ^/forum.php$ /static/test.html permanent;
        
        # 状态码302 地址栏变为http://www.myweb.com/static/test.html
        rewrite ^/forum.php$ http://www.myweb.com/static/test.html last;

#本站 url跳转  url地址栏变化, last、break、redirect都是302
        # 状态码302 地址栏变为http://www.myweb.com/static/test.html
        rewrite ^/forum.php$ http://www.myweb.com/static/test.html last;

		#forum.php状态码301 地址栏变为http://www.myweb.com/static/test.html
        rewrite ^/forum.php$ http://www.myweb.com/static/test.html permanent;
		
# 跳百度
        # forum.php状态码302 地址栏变为 http://www.baidu.com
        rewrite ^/forum.php$ http://www.baidu.com break; # last、redirect也是302
        
		#forum.php状态码301 地址栏变为 http://www.baidu.com
        rewrite ^/forum.php$ http://www.baidu.com permanent;
        location / {...

浏览器Disable cache 访问
    location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ {
        root html; # 绝对路径也可以完成访问   /usr/local/nginx/html;
    }

[root@node1 baidu]# wget -r -x http://fjxplz.com/1004.html


[root@node1 html] mkdir weihu
[root@node1 html]# echo   "维护中...">weihu/index.html

#  http://www.myweb.com   维护
server {
        listen       80;
        server_name www.myweb.com;
        # 3、最终还是跳到维护页面
        rewrite ^/forum.php$ http://www.myweb.com/static/test.html permanent  ;
        
		# 2、加了rewrite后跳转,跟下面的location的上下顺序影响
		rewrite ^/(.*)$ /weihu/index.html last;  # 所有页都跳维护页
        rewrite ^/$ /weihu/index.html last;   # 根页跳到维护页
        #rewrite ^/(.*)$ /weihu/index.html last;
        
        # 1、不加上面的rewrite时,默认首页 
        location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ {
        #    location / {   与上面一样
            root html; # 绝对路径也可以完成访问   /usr/local/nginx/html;
        }        
        
 
# 3、最终还是跳到维护页面
 http://www.myweb.com/forum.php--》static  --》2 /weihu/
192.168.1.11 - -  "GET /forum.php HTTP/1.1" 301 169 "-" "Wget/1.14 (linux-gnu)"
192.168.1.11 - -  "GET /static/test.html HTTP/1.1" 200 13 "-" "Wget/1.14 (linux-gnu)"

server {
        listen       80;
        server_name www.myweb.com;
        # 一直会301跳转,看日志或者wget看下过程
        rewrite ^/(.*)$ /weihu/index.html permanent;  # wget下或者看日志
        
        # 传递参数
        rewrite ^/(.*)$  http://www.baidu.com/$1 permanent;
        
        # myweb.com 跳转到baidu
        if ($host = 'myweb.com') {
        rewrite ^/(.*)$  http://www.myweb.com/$1 permanent;
        }

wget 查看

[root@node1 conf]# wget myweb.com
--2023-10-21 17:32:25--  http://myweb.com/
Resolving myweb.com (myweb.com)... 192.168.1.11
Connecting to myweb.com (myweb.com)|192.168.1.11|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently  # permanent
Location: http://www.myweb.com/ [following]
--2023-10-21 17:32:25--  http://www.myweb.com/	# 跳转后的 
Resolving www.myweb.com (www.myweb.com)... 192.168.1.11
Reusing existing connection to myweb.com:80.
HTTP request sent, awaiting response... 200 OK
Length: 13 [text/html]
Saving to: ‘index.html.2’


# myweb.com 跳转到www.myweb.com
        if ($host = 'myweb.com') {
        rewrite ^/(.*)$  http://www.myweb.com/$1 last; # last不是上面的permanent
        }
[root@node1 conf]# wget myweb.com
--2023-10-21 17:30:57--  http://myweb.com/
Resolving myweb.com (myweb.com)... 192.168.1.11
Connecting to myweb.com (myweb.com)|192.168.1.11|:80... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily #302  last
Location: http://www.myweb.com/ [following]
--2023-10-21 17:30:57--  http://www.myweb.com/	# 跳转后的   
Resolving www.myweb.com (www.myweb.com)... 192.168.1.11
Reusing existing connection to myweb.com:80.
HTTP request sent, awaiting response... 200 OK
Length: 13 [text/html]
Saving to: ‘index.html.1’

多种域名跳转

# 多种域名跳转
	if ($host != 'myweb.com'){
    	rewrite ^/(.*)s http://www.myweb.com/$1 permanent;
    }
# 不存在的页面跳转    
	if ( !-e $request_filename){
	rewrite ^/(.*)$ /weihu/index.html last;
	}

# 火狐浏览器跳转   
	if ($http_user_agent ~ firefox) { 
		rewrite  ^/index.html$  /firefox/index.html;
	}

Nginx:Rewrite跳转+正则表达式+6个生产案列!内容过于真实

https://blog.csdn.net/weixin_48190891/article/details/108532802

Nginx rewrite常用全局变量详细介绍

https://blog.csdn.net/Blue92120/article/details/129003292

upstream lmsManagerAuth-backend {
server 7.180.171.42:8100 max_fails=3 fail_timeout=10s;
}


location ~ ^/edx/lmsManagerAuth/api/datacenter/.*{
  rewrite /edx/lmsManagerAuth/(.*)  /$1 break;  #截取保留重写为api/datacenter/.*
  proxy_pass http://lmsManagerAuth-backend;
www.myweb.com.zh		www.myweb.com/zh
www.myweb.com.en		www.myweb.com/en


在原来的配置文件/usr/local/nginx/conf/nginx.conf的http{}内末尾处加一句:
include /usr/local/nginx/conf.d/*.conf;

[root@node1 nginx]# mkdir -p /usr/local/nginx/conf.d/
[root@node1 nginx]# vim conf.d/www.myng.com.conf
server {
	listen 80;
	server_name www.myng.com;
	location / {
	root /code;
	index index.html;
}
[root@node1 nginx]# mkdir -p /code/{zh,en}

[root@node1 nginx]# echo  zh>/code/zh/index.html
[root@node1 nginx]# echo  en>/code/en/index.html
[root@node1 nginx]# echo code>/code/index.html
[root@node1 html]# curl  www.myng.com
code
[root@node1 html]# curl  www.myng.com/en/
en
[root@node1 html]# curl  www.myng.com/zh/   #浏览器里默认加/ 
zh


server {
	listen 80;
	server_name www.myng.com.zh  www.myng.com.en;
	root /code;
	index index.html;
	location / {
	
        if ($http_host ~* 'zh'){   
        #$http_host 请求的host的
        #$http_accept_language  浏览器请求头里的语言标识
        #$http_user_agent  ~* "iphone|ipad|androaid"   基于agent
        	set $language zh;
        }
        
        if ($http_host ~* 'en'){
        	set $language en;
        }  
        
     	rewrite ^/$ http://www.myng.com/$language redirect;
        
}
http://www.myng.com.zh/     --跳转-->  http://www.myng.com/zh/

curl -Lv

[root@node1 html]# curl -Lv  www.myng.com.zh    #会自动重定向后边指定的网址
* About to connect() to www.myng.com.zh port 80 (#0)
*   Trying 192.168.1.11...
* Connected to www.myng.com.zh (192.168.1.11) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: www.myng.com.zh
> Accept: */*
>
< HTTP/1.1 302 Moved Temporarily
< Server: nginx/1.22.1
< Date: Sun, 22 Oct 2023 12:53:43 GMT
< Content-Type: text/html
< Content-Length: 145
< Connection: keep-alive
< Location: http://www.myng.com/zh
<
* Ignoring the response-body
* Connection #0 to host www.myng.com.zh left intact
* Issue another request to this URL: 'http://www.myng.com/zh'
* About to connect() to www.myng.com port 80 (#1)
*   Trying 192.168.1.11...
* Connected to www.myng.com (192.168.1.11) port 80 (#1)
> GET /zh HTTP/1.1
> User-Agent: curl/7.29.0
> Host: www.myng.com
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.22.1
< Date: Sun, 22 Oct 2023 12:53:43 GMT
< Content-Type: text/html
< Content-Length: 169
< Location: http://www.myng.com/zh/
< Connection: keep-alive
<
* Ignoring the response-body
* Connection #1 to host www.myng.com left intact
* Issue another request to this URL: 'http://www.myng.com/zh/'
* Found bundle for host www.myng.com: 0x2014450
* Re-using existing connection! (#1) with host www.myng.com
* Connected to www.myng.com (192.168.1.11) port 80 (#1)
> GET /zh/ HTTP/1.1
> User-Agent: curl/7.29.0
> Host: www.myng.com
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: nginx/1.22.1
< Date: Sun, 22 Oct 2023 12:53:43 GMT
< Content-Type: text/html
< Content-Length: 3
< Last-Modified: Sun, 22 Oct 2023 11:48:01 GMT
< Connection: keep-alive
< ETag: "65350bf1-3"
< Accept-Ranges: bytes
<
zh
* Connection #1 to host www.myng.com left intact
# 不加-L选项的
[root@node1 html]# curl -v  www.myng.com.zh
* About to connect() to www.myng.com.zh port 80 (#0)
*   Trying 192.168.1.11...
* Connected to www.myng.com.zh (192.168.1.11) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: www.myng.com.zh
> Accept: */*
>
< HTTP/1.1 302 Moved Temporarily
< Server: nginx/1.22.1
< Date: Sun, 22 Oct 2023 12:54:30 GMT
< Content-Type: text/html
< Content-Length: 145
< Connection: keep-alive
< Location: http://www.myng.com/zh
<
<html>
<head><title>302 Found</title></head>
<body>
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.22.1</center>
</body>
</html>
* Connection #0 to host www.myng.com.zh left intact

根据浏览器,agent跳转

server {
	listen 80;
	server_name www.myng.com.zh  www.myng.com.en;
	root /code;
	index index.html;
    location / {
#场景1: 根据用户浏览器的语言,自动跳转至不同的页面。	
        if ($http_accept_language ~* 'zh'){   
        	set $language zh;
        }
        
        if ($http_accept_language ~* 'en'){
        	set $language en;
        }  
        
     	rewrite ^/$ http://www.myng.com/$language redirect;
        
}

#2: 根据用户来源终端设备跳转至不同站点或不同域名
		if ($http_user_agent  ~* "iphone|ipad|androaid"){
        	rewrite ^/$ http://www.myng.com/m;
        }
        
#3:传递跳转的uri
		if ($http_user_agent  ~* "iphone|ipad|androaid"){
        	return 302 http://www.myng.com$request_uri;  #将uri传递
        }
        

api地址跳转

#api.myng.com/bbb   www.myng.com/api/bbb

server {
	listen 80;
	server_name api.myng.com;
	if ($http_host ~* (.*)\.(.*)\.(.*)){
		set $domain $1;
	}
	rewrite ^/(.*)$  http://www.myng.com/$domain/$1 last;
}

维护页面

server {
	listen 80;
	server_name www.myng.com.zh  www.myng.com.en;
	root /code;
	rewrite ^/(.*)$ /wh.html break; #放在server下
	
    location / {...

根据状态码跳转

server {
	listen 80;
	server_name www.myng.com;
	root /code;
	index index.html;
...    
            error_page   500 502 503 504  =@temp;
	location @temp {
		root /data/error
		rewrite ^/(.*)$ /wh.html break; #放在server下	
	}

根据ip区分用户

server {
	listen 80;
	server_name www.myng.com;
	root /code;
	set $ip 0;
	if ($remote_addr ~ "10.0.0.1") { #X-Forwarded-For代理ip
		set $ip 1;
    }
    if  ($ip=0){
    	rewrite  ^/(.*)$ /wh.html break; #放在server下
    }

return 返回跳转

需求: 如果用户请求www.myng.com/test,则返回至ww.xuliangwei.com的url

server {
        listen 80;
        server_name www.myng.com;
        location / {
        
            default_type text/html;# 需要设置--》识别返回字符串
            if ($request_uri  ~* '^/test'){
                return 200 "return test";
                #return 302 http://www.baidu.com;   #302跳转到百度
            }

            root /code;
            index index.html;
        }
}


#浏览器访问:返回
http://www.myng.com/test     return test

last break

当rewrite规则遇到break后,本locationf与其他ocation的所有rewrite/return规则都不再执行。
当rewrite规则遇到last后,本locationh里后续rewrite/return规则不执行,但重写后的url再次从头开始执行所有规则,哪个匹配执行哪个

server {
	listen 80;
	server_name www.myng.com;
	root /code;
	location / {
		#http://www.myng.com/1.html    b.html
		rewrite /1.html /2.html;
            #http://www.myng.com/1.html    2.html
            #rewrite /1.html /2.html break; #break终止,不再匹配
            #http://www.myng.com/1.html    a.html 
            #rewrite /1.html /2.html last; #last终止当前location的匹配
            
		rewrite /2.html /3.html;
	}
	
	location /2.html {
		rewrite /2.html /a.html;
	}
	
	location /3.html {
	rewrite /3.html /b.html;
	}
}

[root@node1 nginx]# echo 1.html>/code/1.html
[root@node1 nginx]# echo 2.html>/code/2.html
[root@node1 nginx]# echo 3.html>/code/3.html
[root@node1 nginx]# echo a.html>/code/a.html
[root@node1 nginx]# echo b.html>/code/b.html
<think>好的,我现在要详细回答用户关于Nginx rewrite规则的问题。首先,我需要整理用户提供的引用内容,提取关键点,并确保回答结构清晰,符合用户的要求。用户希望了解rewrite的详细用法和规则,以及使用示例,所以我要覆盖基本语法、执行顺序、flag标志、正则表达式、与location的配合,以及常见示例。同时,需要引用提供的资料来支持内容,并生成相关问题。 首先,根据引用[5],rewrite的基本语法是rewrite regex replacement [flag];,其中regex是正则,replacement是替换目标,flag可选。需要解释每个部分的作用,并提到支持的flag类型,比如last、break、redirect、permanent,这些在引用[5]的示例中有提到。 然后,执行顺序部分,根据引用[3],Nginx的location匹配优先级会影响rewrite的执行顺序,可能需要按优先级列出,比如精确匹配(=) > 前缀匹配(^~) > 正则匹配(~或~*) > 通用匹配。同时,根据引用[5]中的例子,说明rewrite规则在server块和location块中的执行顺序,比如server块中的rewrite先执行,然后是location中的。 接下来,flag标志的详细说明。根据引用[4]和[5],break会停止当前location的后续rewrite,而last会重新发起请求。需要区分两者的不同,比如break在当前位置终止,而last会重新走匹配流程。redirect和permanent分别对应302和301重定向,这部分引用[5]的示例中有说明。 正则表达式部分需要解释常用符号,如^表示开始,$结束,()捕获组,$1引用,这些在引用[5]的正则例子中都有用到,比如^/html/(.+?).html$和$1的引用。 与location的配合使用,根据引用[2]和[4],可能需要多个location块来处理不同的rewrite规则,因为一旦匹配到某个location,可能不会继续执行其他location中的rewrite。例如,引用[2]的示例中,/test和/yy的location分别处理不同的重写,并且使用last和break标志。 常见示例部分需要包括域名重定向、路径转换、动态参数处理等,这些在引用[5]中有多个例子,比如将/search/key重写为/search.html?keyword=key,使用正则捕获组。同时,引用[3]提到的目录匹配优先级也可能影响示例的选择。 注意事项方面,根据引用[1],需要提到避免过度使用if指令,推荐使用rewrite来保持配置简洁。此外,测试配置和正则调试的重要性,引用[5]中的例子展示了不同的flag效果,需要注意配置后的重载和测试。 最后,生成相关问题,可能需要包括不同flag的区别、正则表达式的编写、与location的优先级问题、性能优化等,确保问题覆盖用户可能关心的其他方面。 现在需要组织这些信息,确保结构清晰,使用中文,正确应用LaTeX格式,引用标记正确,并附上相关问题。需要避免使用Markdown格式,但用户示例中允许代码块,因此可以保留代码示例。同时,确保每个引用来源正确标注,如[^1]、[^2]等。</think>### Nginx rewrite规则详解及使用示例 #### 一、rewrite基本语法 Nginxrewrite指令语法为: $$rewrite\ \ \ regex\ \ \ replacement\ \ \ [flag];$$ 其中: - **regex**:正则表达式,用于匹配请求URI - **replacement**:替换后的目标URI - **flag**:标志位(可选),控制重写行为[^5] #### 二、执行顺序与优先级 1. **server块**中的rewrite规则优先执行 2. 根据location匹配优先级执行: $$(location=) \succ (location\verb|^~|) \succ (location~\*) \succ (location/)$$ [^3] 3. 同一作用域内按配置顺序执行 #### 三、flag标志详解 | 标志 | 行为 | HTTP状态码 | |-----------|----------------------------------------------------------------------|------------| | **last** | 停止当前处理,重新发起请求匹配location | - | | **break** | 立即停止后续所有rewrite规则 | - | | redirect | 返回临时重定向 | 302 | | permanent | 返回永久重定向 | 301 | 示例对比: ```nginx # last会重新匹配location,break直接终止 location / { rewrite ^/a.html /b.html last; # 重新发起请求 rewrite ^/b.html /c.html break; # 终止后续处理[^4] } ``` #### 四、正则表达式关键符号 - `^`:匹配字符串开始(如`^/user`) - `$`:匹配字符串结束(如`.html$`) - `()`:捕获分组,通过`$1`-`$9`引用 - `.*`:匹配任意字符(贪婪模式) - `.+?`:非贪婪匹配 #### 五、典型应用场景 1. **域名重定向** ```nginx rewrite ^/(.*) http://newdomain.com/$1 permanent; [^5] ``` 2. **路径转换** ```nginx rewrite ^/product/(\d+)$ /item?id=$1 break; # 将/product/123转为/item?id=123 ``` 3. **动态参数处理** ```nginx rewrite ^/search/([^/]+)/?$ /search.html?keyword=$1? permanent; [^5] ``` 4. **文件扩展名隐藏** ```nginx rewrite ^/(.*)/$ /$1/index.html; # 将/about/重写为/about/index.html ``` #### 六、与location配合规则 ```nginx location /test { rewrite ^/test/(.*) /yy/$1 last; # 重写后重新匹配location[^2] } location /yy { rewrite ^/yy/(.*) http://baidu.com break; # 直接终止处理链[^2] } ``` #### 七、注意事项 1. 避免过度使用`if`判断,优先使用rewrite实现条件逻辑[^1] 2. 测试时建议先用`redirect`标志观察效果 3. 正则表达式需进行边界限定(如`^`和`$`) 4. 修改配置后需执行`nginx -s reload`重载配置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值