什么是虚拟主机
虚拟主机,就是把一台物理服务器划分成多个“虚拟”的服务器,每一个虚拟主机都可以有独立的域名和独立的目录。
nginx 的虚拟主机就是通过 nginx.conf 中 server 节点指定的,想要设置多个虚拟主机,配置多个 server 节点即可
#user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
配置文件将会有一个专门的章节介绍,先说说server
listen表示虚拟主机的端口号,而server_name表示访问虚拟主机的方式,访问虚拟主机的方式为server_name:listen(即127.0.0.1:80)
server {
listen 8080;
server_name test.com;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
那么想要访问此虚拟主机为test.com:8080
虚拟主机可以根据域名和IP以及不同的端口号进行配置
location
定义虚拟主机资源的路径以及访问方式
location / {
#location 是访问的 url 的匹配设置
root html;
#url 当前匹配后访问的跟目录,root 可以是任意的目录,通常使用 nginx 来作为静态资源服务器
index index.html index.htm;
#默认索引页面
}
当访问为www.test.com,将访问root下(html),默认索引页(index.html)
当访问为www.test.com/2.html,将访问root下(html)的2.html
location可以有多个,可以对location进行配置,根据url来判断,访问指定的location
location配置
语法规则: location [=||*|^~] /uri/ { … }
= 开头表示精确匹配
www.test.com/3.html
location = /3.html {
root html;
}
^~ 开头表示 uri 以某个常规字符串开头,理解为匹配 url 路径即可。
www.test.com/static/a.html
location ^~ /static/ {
root html;
}
~ 开头表示区分大小写的正则匹配
www.test.com/a.htm
location ~ \.(htm) {
root html;
}
.(htm)为正则表达式
~* 开头表示不区分大小写的正则匹配
/ 通用匹配,任何请求都会匹配到。
多个 location 配置的情况下匹配顺序为,首先匹配 =,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配