简述Ngnix的虚拟主机使用

一、虚拟主机:
虚拟主机功能是提供在一台服务器,运行多个网站的功能,有三种模式:多域名;多端口;多ip
多域名的虚拟主机是最常见的一种虚拟主机,也是使用最多的一种方式。下面主要介始下多域名配置方法:
首先要配置DNS服务器,将每个主机名映射到正确的IP地址,然后配置Nginx服务器,使其能识别到不同的主机名就可以了。
主机:172.16.0.9
首先配置DNS,因为是单机演示,没有DNS服务器,这里用host文件来演示。
1.配置host文件
Windows: C:\Windows\System32\drivers\etc
Linux:/etc/hosts

root@backupserver:~# cat /etc/hosts
127.0.0.1       localhost
127.0.1.1       backupserver

172.16.0.9 www.test.com blog.test.com
root@backupserver:~# 

2.创建虚拟主机配置文件:
首先在nignx.conf配置文件http指定块中添加,用include引用这个虚拟主机的配置文件,

include /usr/local/nginx/conf/vhost/*.conf

然后分别创建这两个虚拟主机配置文件:www.test.com.conf与blog.test.com.conf

root@backupserver:~# ls /usr/local/nginx/conf/
fastcgi.conf          fastcgi_params          koi-utf  mime.types          nginx.conf      nginx.conf.default  scgi_params.default  uwsgi_params.default
fastcgi.conf.default  fastcgi_params.default  koi-win  mime.types.default  nginx.conf.bak  scgi_params         uwsgi_params         win-utf
root@backupserver:~# mkdir -p /usr/local/nginx/conf/vhost
root@backupserver:~# vim  /usr/local/nginx/conf/vhost/www.test.com.conf
server {
listen 80;
server_name www.test.com;
location / {
root /usr/local/nginx/html/www;
index index.html index.htm;
}
}

root@backupserver:~# vim /usr/local/nginx/conf/vhost/blog.test.com.conf
server {
listen 80;
server_name blog.test.com;
location / {
root /usr/local/nginx/html/blog;
index index.html index.htm;
}
}

root@backupserver:~# ls /usr/local/nginx/conf/vhost/
blog.test.com.conf  www.test.com.conf
root@backupserver:~# 

3.创建发布目录文件

root@backupserver:/usr/local/nginx/conf/vhost# clear
root@backupserver:/usr/local/nginx/conf/vhost# mkdir /usr/local/nginx/html/www
root@backupserver:/usr/local/nginx/conf/vhost# mkdir /usr/local/nginx/html/blog
root@backupserver:/usr/local/nginx/conf/vhost# echo "this is www.test.com" > /usr/local/nginx/html/www/index.html
root@backupserver:/usr/local/nginx/conf/vhost# echo "this is blog.test.com" > /usr/local/nginx/html/blog/index.html   
root@backupserver:/usr/local/nginx/conf/vhost# 

4.测试:

root@backupserver:/usr/local/nginx/conf/vhost# /usr/local/nginx/sbin/nginx -s reload
root@backupserver:/usr/local/nginx/conf/vhost# curl www.test.com
this is www.test.com
root@backupserver:/usr/local/nginx/conf/vhost# curl blog.test.com
this is www.blog.com
root@backupserver:/usr/local/nginx/conf/vhost# 

你可能感兴趣的:(nginx,linux)