單台Nginx WEB服務器同時會配置N個網站,也可稱之為配置N個虛擬域名的主機,即多個域名對應同一個80端 口。 每個虛擬主機可以是一個獨立網站、可以具有獨立域名,同一台物理機上面的虛擬主機相互之間是獨立。
虛擬主機的類型
基於IP的虛擬主機
可以在一塊物理網卡上綁定多個IP地址。這樣就能夠在使用單一網卡的同一個服務器上運行多個基於IP的虛擬主 機。設置IP別名也非常容易,只須配置系統上的網絡接口,讓它監聽額外的IP地址。
基於端口的虛擬主機
基於端口的虛擬主機配置,使用端口來區分,瀏覽器使用域名或ip地址:端口號訪問。
基於域名的虛擬主機
基於域名的虛擬主機是最常見的一種虛擬主機。只需配置你的DNS服務器,將每個主機名映射到正確的IP地址,然 后配置Nginx服務器,令其識別不同的主機名就可以了。這種虛擬主機技術,使很多虛擬主機可以共享同一個IP地 址,有效解決了IP地址不足的問題。所以,如果沒有特殊要求使你必須用一個基於IP的虛擬主機,最好還是使用基 於域名的虛擬主機。
開始配置實驗!
1.確認nginx已經正常運行
[root@iZ2zecxmcsda0x83lfxjajZ /]# ps -ef|grep nginx root 5704 1 0 Jul10 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx nobody 7290 5704 0 Jul11 ? 00:00:00 nginx: worker process nobody 7291 5704 0 Jul11 ? 00:00:00 nginx: worker process nobody 7292 5704 0 Jul11 ? 00:00:00 nginx: worker process nobody 7293 5704 0 Jul11 ? 00:00:00 nginx: worker process root 8608 8516 0 14:14 pts/0 00:00:00 grep --color=auto nginx
2.重新寫入nginx.conf
#user nobody; worker_processes 4; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http{ include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; sendfile on; keepalive_timeout 65; server{ listen 80; server_name www.test1.com; access_log logs/test1.com.log main; location / { root html/test1; index index.html index.html; } } server{ listen 80; server_name www.test2.com; access_log logs/test2.com.log main; location / { root html/test2; index index.html index.htm; } } }
3.保存后,檢查配置文件是否正確
[root@iZ2zecxmcsda0x83lfxjajZ conf]# /usr/local/nginx/sbin/nginx -t nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
4.重新讀取配置文件
[root@iZ2zecxmcsda0x83lfxjajZ conf]# /usr/local/nginx/sbin/nginx -s reload
5.在html目錄下新建兩個網站目錄test1和test2,並寫入兩個index.html
[root@iZ2zecxmcsda0x83lfxjajZ conf]# mkdir ../html/test1 ../html/test2 && echo "this is test1." > ../html/test1/index.html && echo "this is test2." > ../html/test2/index.html
6.修改hosts文件后,分別訪問www.test1.com和www.test2.com