«

Nginx配置虚拟主机

指尖二进制 • 1 年前 • 847 次点击 • NGINX


[TOC]

Nginx配置虚拟主机:
如果nginx配置文件有一个server就是nginx的默认网站,多个server就是nginx的虚拟主机。
虚拟主机的概念:
虚拟主机:就是把一台物理服务器划分成多个“虚拟”服务器,每一个虚拟主机都可以有独立的域名和独立的目录。

基于端口、基于ip、基于域名:
这里测试的方式有几种方法:
1:网页直接访问
2:elinks 地址 --dump
3:curl 地址

sed -i '/#/d' nginx.conf      把nginx的配置文件注释的去掉
sed -i '/^$/d' nginx.conf     把nginx的配置文件空行的去掉

基于不同端口虚拟主机:

cd /usr/local/nginx/html        默认的页面在这里
cd ..
mkdir www        虚拟主机需要使用创建一个
echo www > www/index.html          生成页面文件
vim conf/nginx.conf
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;
        }
    }
    server {
    listen       8080;
    server_name  localhost;
    location / {
        root   www;
        index  index.html index.htm;
        }
    }
}

重启nginx服务
网页访问:

elinks http://192.168.43.2
elinks http://192.168.43.2:8080

基于不同ip虚拟主机:

硬性条件,必须有两块网卡才能实现:
这里我用虚拟机做的所以需要配置网卡参数:

DEVICE=eth0
ONBOOT=yes
BOOTPROTO=dhcp

DEVICE=eth1
ONBOOT=yes
BOOTPROTO=dhcp

配置nginx:

vim conf/nginx.conf
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"';
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       192.168.43.2: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;
        }
    }
    server {
    listen       192.168.43.132:80;
    server_name  localhost;
    location / {
        root   www;
        index  index.html index.htm;
        }
    }
}

重启nginx服务
网页访问:
http://192.168.43.2
http://192.168.43.132

基于域名虚拟主机:

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  www.a.com;
        location / {
            root   html;
            index  index.html index.htm;
        }
    }
    server {
    listen       80;
    server_name  www.b.com;
    location / {
        root   www;
        index  index.html index.htm;
        }
    }
}

重启nginx:

在 /etc/hosts 文件里必须加上下面两条进行 网页访问测试:
192.168.43.2 www.a.com
192.168.43.2 www.b.com

curl http://www.a.com
curl http://www.b.com
还没收到回复