41 Server_name正则表达式匹配配置
41 Server_name正则表达式匹配配置
41.1 正则表达式匹配
server_name中可以使用正则表达式,并且使用~作为正则表达式字符串的开始标记
常见的正则表达式
| 代码 | 说明 |
| ^ | 匹配搜索字符串开始位置 |
| $ | 匹配搜索字符串结束位置 |
| . | 匹配除换行符\n以外的任何单个字符 |
| \ | 转义字符,将下一个字符标记为特殊字符 |
| [xyz] | 字符集,与任意一个指定字符匹配 |
| [a-z] | 字符范围,匹配指定范围内的任何字符 |
| \w | 与以下任意字符匹配A-Z a-z 0-9 和下划线,等效于 [A-Za-z0-9_] |
| \d | 数字字符匹配,等效于 [0-9] |
| {n} | 匹配n次 |
| {n,} | 至少匹配n次 |
| {n,m} | 匹配至少n次,至多m次 |
| * | 零次或多次,等效于{0,} |
| + | 一次或多次,等效于{1,} |
| ? | 零次或一次,等效于{0,1} |
41.2 演示
[root@nginx-100 /usr/local/nginx/conf]# cat nginx.conf .......... server { listen 80; server_name ~^www\.\w+\.com$; location / { root html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
[root@nginx-100 /usr/local/nginx/conf]# nginx -t && nginx -s reload 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
Windows:C:\Windows\System32\drivers\etc\HOSTS
CentOS:/etc/hosts
# 添加解析 10.0.0.100 www.itheima.com 10.0.0.100 www.itcast.com
浏览器访问:http://www.itcast.com/

浏览器访问:http://www.itheima.com/

41.3 注意
1.正则后不能添加空格
server_name ~ ^www\.\w+\.com$; [root@nginx-100 /usr/local/nginx/conf]# nginx -t nginx: [emerg] empty regex in server name "~" in /usr/local/nginx/conf/nginx.conf:30 nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed
2.括号表达式
通过$1获取对应第一个括号内的内容,以此类推
[root@nginx-100 /usr/local/nginx/conf]# cat nginx.conf .......... server { listen 80; server_name ~^www\.(\w+)\.com$; location / { return 200 '======> access ====> $1'; default_type text/palin; #root html; #index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } } [root@nginx-100 /usr/local/nginx/conf]# nginx -t && nginx -s reload 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
浏览器访问:http://www.itheima.com/

浏览器访问:http://www.itcast.com/

———————————————————————————————————————————————————————————————————————————
无敌小马爱学习
浙公网安备 33010602011771号