利用nginx 虛擬主機、請求轉發實現不一樣端口web訪問

一個服務器上掛一個網站實在是有點浪費;一個服務器上能夠放多個網站;能夠開啓nginx的虛擬主機功能;利用訪問的路徑或者域名不一樣訪問不一樣的文件夾;例如:php

一、一臺服務器上放多個網站使用nginx的配置文件html

這是一個網站的配置文件;nginx

    server {
        listen       80;
        server_name  localhost;
        root    /usr/share/nginx/html;
        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            index  index.html index.htm index.php;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

其中核心配置:配置成以下的形式;便可多個網站經過不一樣的域名進行訪問。原理是經過訪問的host 將對應的服務器目錄返回。git

server {
        listen       80;
        server_name  a.com;//你的域名 ;
        root    /usr/share/nginx/html;
       }

server {
        listen       80;
        server_name  b.com;//二級域名;
        root    /usr/share/nginx/htmlb;//不一樣目錄
       }

二、要是第二個網站的端口監聽的是非80端口;例如gitbook的4000端口;就須要將請求進行轉發;原理是經過不一樣的域名判斷將請求進行轉發;不只要開啓虛擬主機還須要將對應的虛擬主機請求轉發。配置以下:服務器

 
 
server {
        listen       80; server_name a.com;//你的域名 ; root /usr/share/nginx/html; }

server { server_name b.com;//對應的域名 listen
80; location / { proxy_pass http://127.0.0.1:4000; } }

這是配置端口轉發的核心。網站

三、重啓nginxspa

service nginx restart

訪問a.com 對應預配置的文件路徑;訪問b.com 會將請求轉發到4000端口。配置完成後有兩種方式能夠訪問到目錄;rest

第一種能夠直接使用域名進行訪問 b.com ;這種方式默認使用http協議 80端口進行訪問;在服務器端首先會判斷來訪的域名;由對應的虛擬主機處理後將請求轉發到4000端口;code

第二種是經過a.com:4000 (或者b.com:4000 由於a,b域名解析的IP地址是相同的)進行訪問;這種方式直接使用4000端口的監聽程序進行處理請求,並返回數據。server

相關文章
相關標籤/搜索