利用nginx 虚拟主机、请求转发实现不同端口web访问

一个服务器上挂一个网站实在是有点浪费;一个服务器上可以放多个网站;可以开启nginx的虚拟主机功能;利用访问的路径或者域名不同访问不同的文件夹;例如:

1、一台服务器上放多个网站使用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 将对应的服务器目录返回。

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

server {
        listen       80;
        server_name  b.com;//二级域名;
        root    /usr/share/nginx/htmlb;//不同目录
       }

2、要是第二个网站的端口监听的是非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; } }

这是配置端口转发的核心。

3、重启nginx

service nginx restart

访问a.com 对应预配置的文件路径;访问b.com 会将请求转发到4000端口。配置完成后有两种方式可以访问到目录;

第一种可以直接使用域名进行访问 b.com ;这种方式默认使用http协议 80端口进行访问;在服务器端首先会判断来访的域名;由对应的虚拟主机处理后将请求转发到4000端口;

第二种是通过a.com:4000 (或者b.com:4000 因为a,b域名解析的IP地址是相同的)进行访问;这种方式直接使用4000端口的监听程序进行处理请求,并返回数据。

 

posted @ 2017-12-28 16:03  恩恩先生  阅读(8354)  评论(0编辑  收藏  举报