先准备好两个站点:

# tree test1.com/ test2.com/
test1.com/
└── index.html
test2.com/
└── index.html
# cat test1.com/index.html 
test1 test html
# cat test2.com/index.html  
test2 test html


配置Nginx:

# cat nginx.conf
#user  nobody;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    #access_log  logs/access.log  main;
    sendfile        on;
    tcp_nopush     on;
    keepalive_timeout  65;
    gzip  on;
    server {
        listen       80;
        server_name  test1.com;
        access_log      logs/test1.access.log main;
        location / {
            root   /var/www/test1.com;
            index  index.html index.htm;
        }
    }
  
    server {
        listen       80;
        server_name  test2.com;
        access_log      logs/test2.access.log main;
        location / {
            root   /var/www/test2.com;
            index  index.html index.htm;
        }
    }
}


检测配置文件:

# /opt/nginx/sbin/nginx -t
nginx: the configuration file /opt/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /opt/nginx/conf/nginx.conf test is successful

重新加载nginx:

# /opt/nginx/sbin/nginx -s reload


修改本机的hosts文件,通过本机浏览器访问测试效果:

hosts:

192.168.78.131 test1.com
192.168.78.131 test2.com


浏览器访问test1.com 和test2.com 可以访问到不同的虚拟网站。

Nginx-虚拟主机_虚拟主机

Nginx-虚拟主机_虚拟主机_02


更多内容,请关注博主个人博客网站:http://www.whysha.com