添加多個虛擬主機
最近在ubuntu上搗騰nginx,安裝成功了,就只有rewrite沒有試驗,因為服務器上有多個網站,還不敢在服務器上嘗試,慢慢來。網上查了一些文章,下了一篇留下來做試驗。
nginx上虛擬主機的配置其實跟apache上的基本上類似。
需要注意的幾點是:
第一、關于.htaccess配置,也就是為靜態配置,在nginx上一般你要寫在虛擬主機的配置文本中,但是我也有看到用包含文件解決這個問題的,即在虛擬主機配置腳本上include .htaccess文件,不過沒有沒有試過。
第二、計劃好用何種方式運行php,fastcgi?我并不認為在網上流傳的這種辦法是一個好辦法,相反我認為作為一個出色的反向代理服務器應該發揮其反向代理的優勢,所以執行php的方式上請先斟酌好。
好了,回到正題上。
觀察一下nginx的目錄結構,大概你已經知道該怎么做了,跟apache的虛擬主機配置基本類似。
在/etc/nginx/sites-available上新建一個文件,比如叫www.zmynmublwnt.cn吧
然后
1
|
vi www.zmynmublwnt.cn |
加入文件內容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
server { listen [::]:80; server_name www.zmynmublwnt.cn zzvips.com; root /var/www/zzvips.com; 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.zmynmublwnt.cn包含的文件是干啥用的呢?里面是指定php的運行方式,文件緩存等,我不妨把我提示的配置貼一個上來:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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,就不多少說了。
1
2
3
4
5
6
|
location /nginx_status { stub_status on; access_log off; allow all; } |
然后第二步,建立軟連接到sites-enable里面去
1
|
ln -s /etc/nginx/sites-available/www .zzvips.com /etc/nginx/sites-enabled/www .zzvips.com |
你是否需要檢查一下配置語法是不是正確呢?
檢查一下:
1
2
3
|
/etc/init .d /nginx configtest Testing nginx configuration: nginx. |
沒有返回錯誤,重啟nginx就可以了。
/etc/init.d/nginx restart
指定訪問路徑
niginx 似乎沒有虛擬目錄的說法,但是可以指定請求路徑時nginx訪問的路徑,也算是一個解決辦法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
server { listen 80 default; server_name _; location / { root html; index 403.html; } location ~ //.ht { deny all; } location /phpadmin/ { alias /opt/www/phpadmin/; index index.php; } location ~ /.php$ { include httpd.conf; } } |
要注意的是, location /phpadmin/ {} 和 location /phpadmin {} 是完全不同的。
前者可以訪問到目錄,而后者將被重定向到服務器,如: http://127.0.0.1/phpadmin ,將被重定向到 http://_/phpadmin
下面這個配置和上面基本類似,唯一的不同是,所有對 /phpadmin/的訪問將正確解析,而其他訪問則返回頁面不存在(404)的信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
server { listen 80 default; server_name _; location / { root html; #index 403.html; return 404; } location ~ //.ht { deny all; } location /phpadmin/ { alias /opt/www/phpadmin/; index index.php; } location ~ /.php$ { include httpd.conf; } } |