Linux上Nginx如何添加多个虚拟主机配置


最近在ubuntu上捣腾nginx,安装成功了,就只有rewrite没有试验,因为服务器上有多个网站,还不敢在服务器上尝试,慢慢来。网上查了一些文章,下了一篇留下来做试验。
nginx上虚拟主机的配置其实跟apache上的基本上类似。

需要注意的几点是:

第一、关于.htaccess配置,也就是为静态配置,在nginx上一般你要写在虚拟主机的配置文本中,但是我也有看到用包含文件解决这个问题的,即在虚拟主机配置脚本上include .htaccess文件,不过没有没有试过。

第二、计划好用何种方式运行php,fastcgi?我并不认为在网上流传的这种办法是一个好办法,相反我认为作为一个出色的反向代理服务器应该发挥其反向代理的优势,所以执行php的方式上请先斟酌好。

好了,回到正题上。

观察一下nginx的目录结构,大概你已经知道该怎么做了,跟apache的虚拟主机配置基本类似。

在/etc/nginx/sites-available上新建一个文件,比如叫www.blogguy.cn吧

然后
vi www.blogguy.cn
加入文件内容如下:

server
{
listen [::]:80;
server_name www.blogguy.cn blogguy.cn;
root /var/www/blogguy.cn;
index index.html index.htm index.php;
include /etc/nginx/common.conf;
location /nginx_status
{
stub_status on;
access_log off;
allow all;
}
}

简单的解释一下:

listen就是监听端口,不必多说

server_name要多说几句,因为你可能想到了server_alias,其实在nginx中第一个就是server_name,后面的就是server_alias,所以在nginx中server alias name别名是不用另外声明的,这根apache有很大的区别,注意下。

index就是查找网页的先后顺序

include 是包含文件,www.blogguy.cn包含的文件是干啥用的呢?里面是指定php的运行方式,文件缓存等,我不妨把我提示的配置贴一个上来:

location ~* .(ico|css|js|gif|jpe?g|png)(?[0-9]+)?$ {
expires max;
break;
}

location ~ .*.php$ {
# fastcgi_pass 127.0.0.1:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include /etc/nginx/fastcgi_params;

}
if ( $fastcgi_script_name ~ ..*/.*php ) {
return 403;
}

最后 location /nginx_status相当与apache的server-status,就不多少说了。

location /nginx_status
{
stub_status on;
access_log off;
allow all;
}

然后第二步,建立软连接到sites-enable里面去

ln -s /etc/nginx/sites-available/www.blogguy.cn /etc/nginx/sites-enabled/www.blogguy.cn
你是否需要检查一下配置语法是不是正确呢?

检查一下:/etc/init.d/nginx configtest
Testing nginx configuration: nginx.

没有返回错误,重启nginx就可以了。

/etc/init.d/nginx restart

相关内容

    暂无相关文章