图文详解Nginx多种匹配方式

来自:网络
时间:2022-05-18
阅读:
目录

前言

首先建立两个不同的路径的页面做测试

图文详解Nginx多种匹配方式

图文详解Nginx多种匹配方式

然后打开/usr/local/nginx/conf目录下的ngnix.conf

图文详解Nginx多种匹配方式

可以看到

图文详解Nginx多种匹配方式

每一个server都可以定义一个访问的转发到的路径

端口转发

 server {
        listen       878;#当访问878端口组时
        server_name  localhost;
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        location / {
            root   /www/zthwww/w2;#访问878端口时,访问这个路径下的index.html文件
            index  index.html index.htm;
        }
}

重新启动ngnix

 /usr/local/nginx/sbin/nginx -s reload

如果报一下错误,说明是配置文件格式错误,检查配置的server的大括号位置是否匹配,格式是否正确

图文详解Nginx多种匹配方式

测试结果

图文详解Nginx多种匹配方式

 利用访问地址转发

在进行这步操作时,必须确保DNS解析中,已经添加*前缀解析

图文详解Nginx多种匹配方式

然后还是在conf文件中

 server {
        listen       80;
        server_name  zth2.zhangdd1915.top;#修改为任意的XXX.自己域名的格式
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        location / {
            root   /www/zthwww/w1;#指定路径
            index  index.html index.htm;
        }
}

(注意端口号和虚拟主机名不能重复,否则会报错)再次重新启动ngnix

测试

图文详解Nginx多种匹配方式

同一个server可以同时配置多个主机名

例如

 server {
        listen       80;
        server_name  zth2.zhangdd1915.top zth3.zhangdd1915.top;#主机名1 空格 主机名2的形式
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        location / {
            root   /www/zthwww/w1;
            index  index.html index.htm;
        }
}

重启测试

图文详解Nginx多种匹配方式

前置匹配

 server {
        listen       80;
        server_name  *.zhangdd1915.top;#只要是以 .zhangdd1915.top结尾都会匹配到此
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        location / {
            root   /www/zthwww/w1;
            index  index.html index.htm;
        }
}

注意这个一定要写在最前面,因为先写的先匹配,在之前的DNS解析中已经谢了*,所以会自动匹配到默认的,所以要写在首位

重启测试 

图文详解Nginx多种匹配方式

后置匹配

 server {
        listen       878;
        server_name  zhangdd1915.*;
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        location / {
            root   /www/zthwww/w2;
            index  index.html index.htm;
        }
}

 由于我只有一域名,这里就不做测试了。

正则匹配

 server {
        listen       878;
        server_name  ~^[0-9]+\.zhangdd1915\.top$;
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        location / {
            root   /www/zthwww/w1;
            index  index.html index.htm;
        }
}

例如前缀是N个数字开头

总结

返回顶部
顶部