有时为了资源的合理利用,没必要一个站点一个服务器,可以在一个服务器上搭建多个站点来节省资源。
本文以www.test1.com和www.test2.com为例进行说明nginx多站点共用一个服务器的配置。
平台:阿里云ESC 服务器
系统:Ubuntu 16.04
我买的是阿里云香港服务器,没有服务器的可以使用我这个链接进行购买,会有一定的优惠,或者填写我的邀请码 mps4yubn ,会有优惠:
https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=mps4yubn
一、首先安装nginx。
sudo apt-get install nginx
二、创建站点
我们创建两个站点,路径分别为 /var/www/test1/ 和 /var/www/test2/ ,分别在两个路径下放置一个index.html作为站点的测试主页。
mkdir /var/www/test1/
mkdir /var/www/test2/
三、打开 /etc/nginx/nginx.conf,添加下面include语句,保存退出。
include /etc/nginx/vhosts/*conf;
四、建立站点配置文件
使用下面语句在/etc/nginx下创建vhosts文件夹
mkdir /etc/nginx/vhosts
然后分别在vhosts里面建立两个文件 test1.com.conf 、test2.com.conf
cd /etc/nginx/vhosts
vim test1.com.conf
vim test2.com.conf
分别在两个配置文件里填写对应站点的配置信息:
test1.com.conf内容如下:
server {
listen 80 ;
server_name test1.com www.test1.com;
root /var/www/test1;
location / {
index index.php index.html index.htm;
}
location ~* \.php$ {
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:8080;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
test2.com.conf内容如下:
server {
listen 80 ;
server_name test2.com www.test2.com;
root /var/www/test2;
location / {
index index.php index.html index.htm;
}
location ~* \.php$ {
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:8080;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
五、重启nginx服务
service nginx restart
到此,已经完成了 nginx多站点共用一个服务器的配置。 更多的站点配置方法也是一样的,将上面的步骤多做几次就行。
PS:有的人可能还得配置一下/etc/hosts文件
使用下面命令打开hosts文件
vim /etc/hosts
将下面两行添加到文件末尾即可
127.0.0.1 test1.com
127.0.0.1 test2.com