一個服務器上掛一個網站實在是有點浪費;一個服務器上可以放多個網站;可以開啓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端口的監聽程序進行處理請求,並返回數據。