nginx之 nginx虛擬機器配置

張衝andy發表於2017-06-14

 什麼是虛擬主機:

虛擬主機是一種特殊的軟硬體技術,它可以將網路上的每一臺計算機分成多個虛擬主機,每個虛擬主機可以獨立對外提供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


</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;
}
}
}

 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31383567/viewspace-2140750/,如需轉載,請註明出處,否則將追究法律責任。

相關文章