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