概述
- 基于域名的虚拟主机,它是通过什么来进行区分不同的虚拟主机呢?
- 可以有多个server模块通过指定不同的server_name来区分不同的那个虚拟主机
- 可以理解成不同的一个网站域名
server_name 指令用法
1 )语法结构
- 语法:
server_name name1 name2 name3 ...;
- 这是一个固定写法,后面可以跟多个域名
- 示例1:
server_name www.nginx.com;
- 示例2:
server_name *.nginx.org;
- 示例3:
server_name www.nginx.org *.nginx.org;
2 ) 四种写法
server_name www.imooc.com
server_name *.imooc.com
前通配server_name www.imooc.*
后通配server_name ~^www\.imooc\.*$
~ 表示正则匹配
3 )实际演示
nginx.conf
http {
server {
listen 80;
server_name www.nginx-test.com *.nginx-test.com www.nginx-test.*;
root html/nginx-test;
location / {
index index.html;
}
}
}
- $
mkdir nginx-test
- $
touch nginx-test/index.html
<h1> test nginx</h1>
- $
/opt/nginx/sbin/nginx -s reload
- 配置 本机 hosts
192.168.1.23 www.nginx-test.com 192.168.1.23 news.nginx-test.com 192.168.1.23 www.nginx-test.xy
- 浏览器访问
- http://www.nginx-test.com ✅ pass
- http://news.nginx-test.com ✅ pass
- http://www.nginx-test.xy ✅ pass
server_name 指令用法优先级
1 )多域名的匹配
多个域名通常定义不同的 server 块来区分
server {
server_name www.nginx.org
}
server {
server_name www.nginx.*
}
server {
server_name *.nginx.org
}
server {
server_name ~^www\.nginx\.*$
}
- 写了4个 server 块,或某个服务器上部署了多个虚拟主机,应该以哪个为准?
2 )匹配的优先级
- 精确匹配 > 左侧通配符匹配 > 右侧通配符匹配 > 正则表达式匹配
3 )测试
http {
server {
listen 80;
server_name *.nginx-test.com;
root html/nginx-test/left-match;
location / {
index index.html;
}
}
server {
listen 80;
server_name ~^.*\.nginx-test\..*$;
root html/nginx-test/reg-match;
location / {
index index.html;
}
}
server {
listen 80;
server_name www.nginx-test.*;
root html/nginx-test/right-match;
location / {
index index.html;
}
}
server {
listen 80;
server_name www.nginx-test.com;
root html/nginx-test/all-match;
location / {
index index.html;
}
}
}
-
$
mkdir { all-match, left-match, right-match, reg-match }
-
$
touch left-match/index.html
<h1>left-match</h1>
-
$
touch reg-match/index.html
<h1>reg-match</h1>
-
$
touch right-match/index.html
<h1>right-match</h1>
-
$
touch all-match/index.html
<h1>all-match</h1>
-
现在,我们修改下我们的 hosts
192.168.1.23 www.nginx-test.com 192.168.1.23 mail.nginx-test.com 192.168.1.23 doc.nginx-test.xy 192.168.1.23 www.nginx-test.org 192.168.1.23 www.nginx-test.cn 192.168.1.23 sport.nginx-test.cc
浏览器访问测试
1 )访问 http://www.nginx-test.com
- 会显示 all-match
- 如果注释掉 all-match 相关 server 块,重新加载 nginx, 则显示 left-match
2 ) 访问 http://mail.nginx-test.com 或 http://doc.nginx-test.com
- 会显示 left-match
3 ) 访问 http://www.nginx-test.org 或 http://www.nginx-test.cn
- 会显示 right-match
4 ) 访问 http://sport.nginx-test.cc
- 会显示 reg-match