Nginx實現虛擬主機
通過nginx可以實現虛擬主機的配置,nginx支持三種類型的虛擬主機配置
-
基於ip的虛擬主機, (一塊主機綁定多個ip地址)
-
基於域名的虛擬主機(servername)
-
基於端口的虛擬主機(listen如果不寫ip端口模式)
基於ip的虛擬主機
編輯配置文件
user root;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# 基於ip的虛擬主機 - ip1
server {
listen 182.61.200.6:80;
server_name www.vhost-ip1.com;
location / {
root html;
index vhost-ip1/index.html;
}
}
# 基於ip的虛擬主機 - ip2
server {
listen 192.168.1.9:80;
server_name www.vhost-ip2.com;
location / {
root html;
index vhost-ip2/index.html;
}
}
}
創建網站目錄及文件
在nginx的目錄下創建2個網站目錄
創建目錄
mkdir vhost-ip1
編寫一個html文件
vim index.html
內容如下
測試搭建虛擬主機 ip1
複製該文件夾
cp -rf vhost-ip1 vhost-ip2
將vhost-ip2目錄下的index.html的內容改爲下面的內容
測試搭建虛擬主機 ip2
基於域名的虛擬主機
編輯配置文件
user root;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# 基於域名的虛擬主機 - ip1
server {
listen 80;
server_name v1.vhost.com;
location / {
root html;
index vhost-ip1/index.html;
}
}
# 基於域名的虛擬主機 - ip2
server {
listen 80;
server_name v2.vhost.com;
location / {
root html;
index vhost-ip2/index.html;
}
}
}
重新加載配置
sbin/nginx -s reload
配置hosts
配置hosts
vim /etc/hosts
添加內容
127.0.0.1 v1.vhost.com
127.0.0.1 v2.vhost.com
訪問測試
curl v1.vhost.com
curl v2.vhost.com
基於端口的虛擬主機
編輯配置文件
user root;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# 基於端口的虛擬主機 - port1
server {
listen 81;
server_name localhost;
location / {
root html;
index vhost-ip1/index.html;
}
}
# 基於端口的虛擬主機 - port2
server {
listen 82;
server_name localhost;
location / {
root html;
index vhost-ip2/index.html;
}
}
}
重新加載配置
sbin/nginx -s reload
訪問測試
訪問81端口
瀏覽器訪問http://192.168.1.7:81
訪問82端口
瀏覽器訪問http://192.168.1.7:82