1. 程式人生 > >Nginx系列-3.配置Nginx虛擬主機

Nginx系列-3.配置Nginx虛擬主機

Linux Nginx

Nginx系列-3.配置Nginx虛擬主機

目錄 - Nginx系列

Nginx系列-1.Linux下安裝Nginx
Nginx系列-2.配置LNMP(Linux、Nginx、MySQL、PHP)架構
Nginx系列-3.配置Nginx虛擬主機
Nginx系列-4.Nginx日誌配置及日誌切割
Nginx系列-5.配置Nginx的防盜鏈
Nginx系列-6.配置Nginx的HTTPS
Nginx系列-7.配置Nginx使用uwsgi支持web.py框架
Nginx系列-8.配置Nginx+Apache實現動靜分離
Nginx系列-9.配置NFS實現Nginx實現動靜分離
Nginx系列-10.采用Nginx搭建正向代理服務

Nginx系列-11.配置Nginx反向代理和負載均衡


實驗環境
一臺最小化的 CentOS 7.3 虛擬機
IP: 192.168.204.135

一、配置基本環境

  1. 安裝nginx

    yum install -y epel-*
    yum isntall -y nginx vim
  2. 建立虛機主機的站點根目錄

    mkdir /var/wwwroot
    mkdir /var/wwwroot/site1
    mkdir /var/wwwroot/site2
    echo -e "site1" >> /var/wwwroot/site1/index.html
    echo -e "site2" >> /var/wwwroot/site2/index.html

    技術分享圖片

  3. 關閉CentOS的防火墻
    setenforce 0
    systemctl stop firewalld
    systemctl disable firewalld

    技術分享圖片

二、配置基於端口的虛擬主機

  1. 編輯nginx配置文件
    vim /etc/nginx/conf.d/vhosts.conf
  2. 添加以下內容

    server {
    listen 8081;
    root /var/wwwroot/site1;
    index index.html;
    
    location / {
    }
    }
    server {
    listen 8082;
    root /var/wwwroot/site2;
    index index.html;
    
    location / {
    }
    }

    技術分享圖片

  3. 啟動nginx服務

    systemctl start nginx
  4. 在宿主機訪問兩個站點
    http://192.168.204.135:8081/
    http://192.168.204.135:8082/
    技術分享圖片
    技術分享圖片

三、配置基於域名的虛擬主機

  1. 重新編輯nginx配置文件

    vim /etc/nginx/conf.d/vhosts.conf
  2. 刪除原內容,重新添加以下內容

    server {
    listen 80;
    server_name site1.test.com;
    root /var/wwwroot/site1;
    index index.html;
    
    location / {
    }
    }
    server {
    listen 80;
    server_name site2.test.com;
    root /var/wwwroot/site2;
    index index.html;
    
    location / {
    }
    }

    技術分享圖片

  3. 重啟nginx服務

    systemctl restart nginx
  4. 在Windows上修改hosts文件
    編輯C:\Windows\System32\drivers\etc\hosts文件,
    添加以下內容(根據實際情況自己修改)

    192.168.204.135   site1.test.com  
    192.168.204.135   site2.test.com

    技術分享圖片

  5. 在宿主機訪問兩個站點
    http://site1.test.com/
    http://site2.test.com/
    技術分享圖片
    技術分享圖片

四、配置基於IP的虛擬主機

  1. 在虛擬機增加兩個IP地址

    ifconfig ens33:1 192.168.204.151
    ifconfig ens33:2 192.168.204.152
  2. 重新編輯nginx配置文件

    vim /etc/nginx/conf.d/vhosts.conf
  3. 刪除原內容,重新添加以下內容

    server {
    listen 192.168.204.151:80;
    root /var/wwwroot/site1;
    index index.html;
    
    location / {
    }
    }
    server {
    listen 192.168.204.152:80;
    root /var/wwwroot/site2;
    index index.html;
    
    location / {
    }
    }

    技術分享圖片

  4. 重啟nginx服務

    systemctl restart nginx
  5. 在宿主機訪問兩個站點
    http://192.168.204.151/
    http://192.168.204.152/
    技術分享圖片
    技術分享圖片

Nginx系列-3.配置Nginx虛擬主機