nginx中应用正则表达式
|
admin
2025年6月28日 22:30
本文热度 24
|
- nginx配置
# ^测试
location ~ ^/imgs {
return 200 "匹配/imgs开头的正则表达式";
}
- 测试
### ngxinx响应:匹配/imgs开头的正则表达式
GET http://localhost:85/imgs/123
- nginx配置
# $测试
location ~ \.js$ {
return 200 "匹配js文件";
}
- 测试
### ngxinx响应:匹配js文件
GET http://localhost:85/http.js
- nginx配置
# [abc]测试
location ~ [a-zA-Z].html$ {
return 200 "匹配英文字母的html";
}
- 测试
### ngxinx响应:匹配英文字母的html
GET http://localhost:85/demo.html
### ngxinx响应:404 Not Found。因为demo1中含有数据不合规则
GET http://localhost:85/demo1.html
- nginx配置
location ~ ^/users?$ {
return 200 "匹配user结尾 或 users结尾";
}
- 测试
### ngxinx响应:匹配user结尾 或 users结尾
GET http://localhost:85/user
### ngxinx响应:匹配user结尾 或 users结尾
GET http://localhost:85/users
### ngxinx响应:匹配user结尾 或 users结尾。因为nginx的locaton匹配的是URI(统一资源标识符),不是URL(统一资源定位符),URL比URI范围更广,URL还包含查询参数如?id=123、片段标识符如#section1
GET http://localhost:85/user?name=abc
### ngxinx响应:404 Not Found。不符合匹配规则。
GET http://localhost:85/usernames
- nginx配置
# +测试、\w测试,匹配多个路径参数,/\w+表示路径参数,(/\w+)+表示1个以个路径参数,((/\w+)+)+将多个路径参数分组
location ~ ^/api((/\w+)+)+$ {
return 200 $1;
}
- 测试
### ngxinx响应:404 Not Found。没有路径参数匹配不到
GET http://localhost:85/api
### ngxinx响应:/user。匹配1个路径/user
GET http://localhost:85/api/user
### ngxinx响应:/user/books
GET http://localhost:85/api/user/books
### ngxinx响应:/user/book/12
GET http://localhost:85/api/user/book/12
- nginx配置
# *测试、\w测试,匹配0或多个路径参数
location ~ ^/dev-api((/\w+)+)*$ {
return 200 $1;
}
- 测试
### ngxinx响应: Response code: 200 (OK) <Response body is empty>。匹配0个参数路径
GET http://localhost:85/dev-api
### ngxinx响应:/user
GET http://localhost:85/dev-api/user
### ngxinx响应:/user/books
GET http://localhost:85/dev-api/user/books
### ngxinx响应:/user/book/123
GET http://localhost:85/dev-api/user/book/123
- nginx配置
# .测试 匹配换行符以外的其它字符
location ~ ^/others/(.+)+$ {
return 200 $1;
}
- 测试
### ngxinx响应:asdfas2435!@
GET http://localhost:85/others/asdfas2435!@#
### ngxinx响应:404 Not Found。因为包含%0a,%0a为urlencode后的换行符
GET http://localhost:85/others/asdfas%0a2435!@#
- nginx配置
# \W测试,匹配非数字、非字母、非下划线
location ~ ^/W/(\W+)$ {
return 200 $1;
}
- 测试
### nginx响应:!@#$%^&*()
GET http://localhost:85/W/!%40%23%24%25%5E%26*()
### nginx响应:404 Not Found。不符合规则,含有数字和字母
GET http://localhost:85/W/!%40%23%24%25%5E%26*()123abc
- nginx配置
# \d测试,匹配数字
location ~ ^/num/(\d+)$ {
return 200 $1;
}
- 测试
### nginx响应:123
GET http://localhost:85/num/123
### nginx响应:404 Not Found。不符合规则
GET http://localhost:85/num/abc
- nginx配置
# \s测试,匹配\n和\t
location ~ ^/empty((/\s+)+)+$ {
return 200 $1;
}
- 测试
### nginx响应:/ %0a:换行符
GET http://localhost:85/empty/%0a
### nginx响应:/ / %09:制表符
GET http://localhost:85/empty/%09/%09
- 分组编号:从左至右从1开始号,每遇到一个左括号编号就加1
阅读原文:原文链接
该文章在 2025/7/1 23:40:17 编辑过