Nginx Rewrite 的相关功能


Nginx 中 rewrite 指令详解

Nginx 的 rewrite 指令是一个非常强大的工具,用于重写 URL,实现 URL 重定向或内部重写,从而帮助你实现灵活的 URL 处理和优化 SEO。

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

1. rewrite 指令的基本语法

rewrite 指令的基本语法如下:

rewrite [flag] pattern replacement [flag];
  • pattern:用于匹配 URL 的模式。
  • replacement:用于替换匹配到的 URL 的新值。
  • flag:可选标志,用于控制 rewrite 指令的行为。

2. ngx_http_rewrite_module 模块指令

2.1 if指令

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

if (条件匹配) {
action
}

使用正则表达式对变量进行匹配,匹配成功时if指令认为条件为true,否则认为false,变量与表达式之间
使用以下符号链接:

= #比较变量和字符串是否相等,相等时if指令认为该条件为true,反之为false != #比较变量和字符串是否不相等,不相等时if指令认为条件为true,反之为false ~ #区分大小写字符,可以通过正则表达式匹配,满足匹配条件为真,不满足匹配条件为假 !~ #区分大小写字符,判断是否匹配,不满足匹配条件为真,满足匹配条件为假 ~* #不区分大小写字符,可以通过正则表达式匹配,满足匹配条件为真,不满足匹配条件为假 !~* #不区分大小字符,判断是否匹配,满足匹配条件为假,不满足匹配条件为真

-f 和 !-f #判断请求的文件是否存在和是否不存在
-d 和 !-d #判断请求的目录是否存在和是否不存在
-x 和 !-x #判断文件是否可执行和是否不可执行
-e 和 !-e #判断请求的文件或目录是否存在和是否不存在(包括文件,目录,软链接)
#注意:
#如果KaTeX parse error: Expected 'EOF', got '#' at position 41: …lse,其他条件为true。 #̲nginx 1.0.1之前变量的值如果以0开头的任意字符串会返回false

示例

location /test {
index index.html;
default_type text/html;
if ( $scheme = http ){
echo "if ---------> $scheme";
}
if ( $scheme = https ){
echo "if ---------> $scheme";
}
}
location /test2 {
if ( !-e $request_filename ){
echo "$request_filename is not exist";
return 409}
}
测试:
[root@client ~]# curl test.example.org/test/
if ---------> http
[root@client ~]# curl test.example.org/test2/test
/webdata/nginx/example.org/test/test2/test is not exist

2.2 set指令

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

示例

[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhosts.conf
server {
listen 80;
server_name test.example.org;
root /webdata/nginx/example.org/test;
location /test3{
set $name example;
echo $name;
}
}
测试:
[root@client ~]# curl test.example.org/test3
example

2.3 break指令

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

[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhosts.conf
server {
listen 80;
server_name test.example.org;
root /webdata/nginx/example.org/test;
location /break{
default_type text/html;
set $name test;
echo $name;
break;
set $port $server_port;
echo $port;
}
}
[root@client ~]# curl test.example.org/break #当未添加break时
test
80
[root@client ~]# curl test.example.org/break #添加break后
test

2.4 return指令

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

return code; #返回给客户端指定的HTTP状态码
return code [text]; #返回给客户端的状态码及响应报文的实体内容
#可以调用变量,其中text如果有空格,需要用单或双引号
return code URL; #返回给客户端的URL地址

示例

server {
listen 80;
server_name test.example.org;
root /webdata/nginx/example.org/test;
location /return {
default_type text/html;
if ( !-e $request_filename){
return 301 http://www.baidu.com;
#return 666 "$request_filename is not exist";
}
echo "$request_filename is exist";
}
}
测试:
[root@client ~]# curl test.example.org/return
/webdata/nginx/example.org/test/return is exist
[root@client ~]# curl test.example.org/return1
/webdata/nginx/example.org/test/return1 is not exist
#测试return 301 http://www.baidu.com;
可在浏览器直接访问test.example.org/return1

return示例

location /test {
default_type application/json;
return 200 '{"status:"success"}';
}

3. rewrite 指令的使用场景

3.1 内部重写

内部重写用于将 URL 重写为内部 URL,但客户端看到的仍然是原始 URL。

示例

假设你想要将所有 /old/ 开头的请求重写为 /new/

location /old/ {
    rewrite ^/old/(.*) /new/$1 last;
}

这里,rewrite 指令使用正则表达式 ^/old/(.*) 匹配 /old/ 开头的所有请求,并将其重写为 /new/ 加上捕获的第一组内容。

3.2 重定向

重定向用于将客户端请求重定向到新的 URL。

示例

假设你想要将所有 /old/ 开头的请求永久重定向到 /new/

location /old/ {
    rewrite ^/old/(.*) /new/$1 permanent;
}

这里,rewrite 指令使用 permanent 标志返回一个 HTTP 301 状态码,告知客户端永久重定向到新的 URL。

3.3 URL 规范化

URL 规范化用于确保 URL 的一致性,比如统一大小写或去除尾部斜杠。

示例

假设你想要规范化 URL,确保所有 URL 都以 / 结尾:

location / {
    if (!-d $request_filename) {
        rewrite ^(.*)$ /$1/ redirect;
    }
}

这里,rewrite 指令只有在请求的文件名不是目录时才生效,并将 URL 重定向为带有尾部斜杠的 URL。

3.4 SEO 优化

SEO 优化可以通过重写 URL 来实现更好的搜索引擎排名。

示例

假设你想要将 /product.php?id=123 重写为 /product/123

location /product.php {
    rewrite ^/product\.php\?id=(\d+)$ /product/$1 last;
}

这里,rewrite 指令使用正则表达式捕获数字 ID,并将其重写为更加友好的 URL。

3.5 条件重写

你可以使用 if 指令与 rewrite 指令结合使用,实现基于条件的重写。

示例

假设你想要根据客户端的 IP 地址重定向到不同的 URL:

if ($remote_addr = 127.0.0.1) {
    rewrite ^/ /internal last;
} else {
    rewrite ^/ /public last;
}

这里,rewrite 指令根据客户端的 IP 地址重定向到不同的 URL。

3.6 结合 map 指令

map 指令可以与 rewrite 指令结合使用,实现更复杂的条件逻辑。

示例

假设你想要根据客户端的 User-Agent 字段重定向到不同的 URL:

map $http_user_agent $user_agent_type {
    default  "unknown";
    "~MSIE" "ie";
    "~Firefox" "firefox";
    "~Chrome" "chrome";
}

if ($user_agent_type = "ie") {
    rewrite ^/ /ie last;
} else if ($user_agent_type = "firefox") {
    rewrite ^/ /firefox last;
} else if ($user_agent_type = "chrome") {
    rewrite ^/ /chrome last;
}

这里,map 指令根据 User-Agent 字段的值映射到不同的变量,然后 rewrite 指令根据这个变量的值重定向到不同的 URL。

3.7 重写查询字符串

你可以使用 rewrite 指令来修改或删除查询字符串。

示例

假设你想要删除 URL 中的 utm_source 参数:

rewrite ^/(.*)\?utm_source=[^&]+(.*)$ /$1?$2 last;

这里,rewrite 指令使用正则表达式删除 utm_source 参数。

3.8 重写 URL 中的片段标识符

你可以使用 rewrite 指令来修改 URL 中的片段标识符。

示例

假设你想要将 URL 中的 #section1 替换为 #section2

rewrite ^/(.*)(#.*)$ /$1#section2 last;

这里,rewrite 指令使用正则表达式替换 URL 中的片段标识符。

4. rewrite 指令的高级用法

4.1 使用变量

rewrite 指令可以结合变量使用,实现更复杂的逻辑。

示例

假设你想要根据客户端的 IP 地址重定向到不同的 URL:

set $ip $remote_addr;
if ($ip = 127.0.0.1) {
    rewrite ^/ /internal last;
} else {
    rewrite ^/ /public last;
}

这里,rewrite 指令根据客户端的 IP 地址重定向到不同的 URL。

4.2 结合 if 指令

rewrite 指令可以与 if 指令结合使用,实现条件重写。

示例

假设你想要在维护模式下重定向所有请求:

if ($http_host = "example.com") {
    rewrite ^/(.*)$ /maintenance last;
}

这里,rewrite 指令只有在 http_host"example.com" 时才会生效。

4.3 使用正则表达式

rewrite 指令可以使用正则表达式来匹配 URL。

示例

假设你想要将所有以 .html 结尾的 URL 重写为去掉 .html 的 URL:

rewrite ^/(.*).html$ /$1 last;

这里,rewrite 指令使用正则表达式捕获 .html 前面的部分,并将其重写为去掉 .html 的 URL。

4.4 使用多个 rewrite 指令

你可以在一个 location 块中使用多个 rewrite 指令,实现复杂的 URL 重写逻辑。

示例

假设你想要先规范化 URL,然后重定向到一个新的 URL:

location / {
    if (!-d $request_filename) {
        rewrite ^(.*)$ /$1/ redirect;
    }
    rewrite ^/old/(.*) /new/$1 permanent;
}

这里,rewrite 指令首先规范化 URL,然后将 URL 重定向到新的 URL。

5. 注意事项

  • 使用 rewrite 指令时要小心避免无限循环。
  • 确保 rewrite 指令的顺序正确,以避免意外的结果。
  • 使用 rewrite 指令时要考虑到 SEO 影响,避免不必要的重定向链。
  • 测试 rewrite 规则的有效性,确保它们按预期工作。
  • 当使用正则表达式时,确保正则表达式的准确性,以避免误匹配或漏匹配。
  • 17
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值