對於小流量的網站來說,在nginx服務器上只運行一個網站太浪費服務器資源了,如果我們的公司有多個網站業務,在一臺服務器上同時運行多個網站,不禁能充分利用起服務器的性能,還能減少公司成本。那麼這個功能如何實現呢?
我們先來看一看nginx的配置文件:
vim /usr/local/nginx/conf/nginx.conf
http
{
server
{
listen 81; #監聽的端口,前邊可添加IP。
server_name localhost; #主機名
access_log logs/access.log combined; #日誌位置
location /
{
root html; #網頁文件存放的目錄
index index.html index.htm; #默認首頁文件,優先級從左到右
}
}
}
只需要看這一部分就可以了。每一個server模塊(紅色部分)就相當於一臺獨立的主機。我們只需要在http模塊中添加sever即可。
示例:
如果我們有a、b兩個網站,分別爲www.a.com和www.b.com,同時在這臺nginx中運行。首先需要在網站主目錄中添加兩個目錄如www.a.com和www.b.com:
mkdir /usr/local/nginx/html/www.a.com
mkdir /usr/local/nginx/html/www.b.com
在兩個目錄中分別添加兩個index.html文件內容分別爲:
This is A!
This is B!
然後修改nginx配置文件的http部分內容爲:
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 81;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
}
server {
listen 81;
server_name www.a.com;
access_log logs/www.a.com.access.log combined;
location / {
root html/www.a.com;
index index.html index.htm;
}
}
server {
listen 81;
server_name www.b.com;
access_log logs/www.b.com.access.log combined;
location / {
root html/www.b.com;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
然後重啓nginx服務後訪問網站:
http://115.159.184.248:81/a/ -------- This is A!
http://115.159.184.248:81/b/ -------- This is B!
這樣,簡單的虛擬主機便配置好了。