什麼是虛擬主機
虛擬主機,就是把一臺物理服務器劃分成多個“虛擬”的服務器,每一個虛擬主機都可以有獨立的域名和獨立的目錄。
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 配置的情況下匹配順序爲,首先匹配 =,其次匹配^~, 其次是按文件中順序的正則匹配,最後是交給 / 通用匹配