nginx虛擬主機配置


nginx虛擬主機配置

 
虛擬主機的概念

虛擬主機,就是把一台物理服務器划分成多個“虛擬”的服務器,每一個虛擬主機都可以有獨立的域名和獨立的目錄

nginx虛擬主機的配置

nginx的虛擬主機就是通過nginx.conf中server節點指定的,想要設置多個虛擬主機,配置多個server節點即可

先看一個最簡單的虛擬主機配置示例

server { 
listen 80; 
server_name a.test.com; 

location / { 
index index.html; 
root /home/www/host_a/; 

}

listen 80; 

指定這個虛擬主機監聽的是80端口

server_name a.test.com; 

指定這個虛擬主機名為a.test.com,當用戶訪問a.test.com時,就有這個虛機主機進行處理

虛擬主機名可以有4種格式:

(1)准確的名字,例如此例中的a.test.com

(2)*號開頭的,例如 *.test.com

(3)*號結尾的,例如 mail.*

(4)正則表達式形式,例如 

server_name ~^www\d+\.test\.com$; 

注意,使用正則表達式形式時,必須以'~'開頭

server_name也可以同時指定多個,例如:

server_name test.com www.test.com *.test.com;

這時優先級為:

(1)確切的名字

(2)最長的以*起始的通配符名字

(3)最長的以*結束的通配符名字

(4)第一個匹配的正則表達式名字

location / 

因為所有請求都是/開頭的,所以這行表示匹配所有請求

index index.html; 

指定此虛擬主機的默認首頁為index.html

root /home/www/host_a/;

指定此虛擬主機的物理根目錄為/home/www/host_a/

案例

(1)對兩個域名配置相應的虛擬主機,指定不同的目錄

a.test.com -> /home/www/a

b.test.com -> /home/www/b

配置

server { 
listen 80; 
server_name a.test.com; 

#開啟網站目錄文件列表功能,訪問目錄時列出其中的文件列表,默認不開啟
autoindex on; 

index index.html; 
root /home/www/a/; 
}

server { 
listen 80; 
server_name b.test.com; 

index index.html; 
root /home/www/b/; 

#禁止對self目錄的訪問
location /(self)/ { 
deny all; 

}

(2)對不同訪問目錄指定不同物理目錄

server {
listen 80;

#使用正則格式,這里表示接受任何ip
server_name ~^\d+\.\d+\.\d+\.\d+$;

index index.html index.htm;
root /home/lg/www/;

location /share {
root /home/lg/Downloads;
}

location ^~ /Videos {
root /home/lg/;
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
allow all;
}

location ^~ /html5 {
root /home/lg/workspace/nodejs/;
index index.html index.htm;
}

location = /404.html {
root /usr/share/nginx/html;
}
}

autoindex_exact_size
默認為on,顯示出文件的確切大小,單位是bytes
改為off后,顯示出文件的大概大小,單位是kB或者MB或者GB

autoindex_localtime
默認為off,顯示的文件時間為GMT時間。
改為on后,顯示的文件時間為文件的服務器時間

allow all;
允許所以訪問

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM