什么是虛擬主機:
虛擬主機是一種特殊的軟硬件技術,它可以將網絡上的每一台計算機分成多個虛擬主機,每個虛擬主機可以獨立對外提供www服務,這樣就可以實現一台主機對外提供多個web服務,每個虛擬主機之間是獨立的,互不影響。
nginx可以實現虛擬主機的配置,nginx支持三種類型的虛擬主機配置。
1、基於域名的虛擬主機 (server_name來區分虛擬主機——應用:外部網站)
2、基於ip的虛擬主機, (一塊主機綁定多個ip地址)
3、基於端口的虛擬主機 (端口來區分虛擬主機——應用:公司內部網站,外部網站的管理后台)
范例:
一、 基於域名的虛擬主機
1、配置通過域名區分的虛擬機
[root@mysql03 nginx]# cat conf/nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name www.nginx01.com;
location / {
root html;
index index.html index.htm;
}
}
server {
listen 80;
server_name www.nginx02.com;
location / {
root /root/html;
index index.html index.htm;
}
}
}
2、 為 域名為 www.nginx02.com 的虛擬機,創建 index 文件
[root@mysql03 ~]# mkdir -p /root/html
[root@mysql03 ~]# cd /root/html/
[root@mysql03 html]# vi index.html
[root@mysql03 html]# cat index.html
<html>
<p>
this is my nginx
</p>
</html>
3、重新加載配置文件
[root@mysql03 nginx]# ./sbin/nginx -s reload
4、客戶端配置路由映射
在 C:\Windows\System32\drivers\etc\hosts 文件中添加兩行
10.219.24.26 www.nginx01.com
10.219.24.26 www.nginx02.com
如圖:
5、 測試訪問
瀏覽器輸入:http://www.nginx01.com/
瀏覽器輸入:http://www.nginx02.com/
>成功!
補充:如果配置不能正常訪問, 試參考 http://blog.csdn.NET/zhang123456456/article/details/73252148
二、 基於ip的虛擬主機
1. 一塊網卡綁定多個ip
[root@mysql03 nginx]# ifconfig eth0:1 10.219.24.27
[root@mysql03 nginx]# ifconfig
eth0 Link encap:Ethernet HWaddr 00:0C:29:79:F4:02
inet addr:10.219.24.26 Bcast:10.255.255.255 Mask:255.0.0.0
...
eth0:1 Link encap:Ethernet HWaddr 00:0C:29:79:F4:02
inet addr:10.219.24.27 Bcast:10.255.255.255 Mask:255.0.0.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
2. 配置通過ip區分的虛擬機
[root@mysql03 nginx]# cat conf/nginx.conf
user root root; #說明:這里的user根據 自己的nginx.conf文件所在的目錄的屬主屬性而定
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 10.219.24.26:80;
server_name www.nginx01.com;
location / {
root html;
index index.html index.htm;
}
}
server {
listen 10.219.24.27:80;
server_name www.nginx01.com;
location / {
root /root/html;
index index.html index.htm;
}
}
}
3. reopen nginx
[root@mysql03 nginx]# ./sbin/nginx -s reopen
補充:
-- 刪除綁定的vip
ifconfig eth0:1 10.219.24.27 down
三、 基於端口的虛擬主機
配置通過端口區分的虛擬機
[root@mysql03 nginx]# cat conf/nginx.conf
user root root; #說明:這里的user根據 自己的nginx.conf文件所在的目錄的屬主屬性而定
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name www.nginx01.com;
location / {
root html;
index index.html index.htm;
}
}
server {
listen 8080;
server_name www.nginx01.com;
location / {
root /root/html;
index index.html index.htm;
}
}
}