1. 程式人生 > >Nginx技巧——在Server_Name指令中使用正則表示式

Nginx技巧——在Server_Name指令中使用正則表示式

nginx中的server_name指令主要用於配置基於名稱虛擬主機,server_name指令在接到請求後的匹配順序分別為:

1、準確的server_name匹配,例如:

server {
    listen       80;
    server_name  howtocn.org  www.howtocn.org;
    ...
}

2、以*萬用字元開始的字串:

server {
    listen       80;
    server_name  *.howtocn.org;
    ...
}

3、以*萬用字元結束的字串:

server {
    listen       80;
    server_name  www.*;
    ...
}

4、匹配正則表示式:

server {
    listen       80;
    server_name  ~^(?<www>.+)\.howtocn\.org$;
    ...
}

nginx將按照1,2,3,4的順序對server name進行匹配,只有有一項匹配以後就會停止搜尋,所以我們在使用這個指令的時候一定要分清楚它的匹配順序(類似於location指令)。

server_name指令一項很實用的功能便是可以在使用正則表示式的捕獲功能,這樣可以儘量精簡配置檔案,畢竟太長的配置檔案日常維護也很不方便。

二、例項

下面是2個具體的應用:

1、在一個server塊中配置多個站點

server
  {
    listen       80;
    server_name  ~^(www\.)?(.+)$;
    index index.php index.html;
    root  /data/wwwsite/$2;
  }

站點的主目錄應該類似於這樣的結構:

/data/wwwsite/howtocn.org
/data/wwwsite/linuxtone.org
/data/wwwsite/baidu.com
/data/wwwsite/google.com

這樣就可以只使用一個server塊來完成多個站點的配置。

2、在一個server塊中為一個站點配置多個二級域名

實際網站目錄結構中我們通常會為站點的二級域名獨立建立一個目錄,同樣我們可以使用正則的捕獲來實現在一個server塊中配置多個二級域名:

server
  {
    listen       80;
    server_name  ~^(.+)?\.howtocn\.org$;
    index index.html;
    if ($host = howtocn.org){
        rewrite ^ http://www.howtocn.org permanent;
    }
    root  /data/wwwsite/howtocn.org/$1/;
  }

站點的目錄結構應該如下:

/data/wwwsite/howtocn.org/www/
/data/wwwsite/howtocn.org/nginx/

這樣訪問http://www.howtocn.org時root目錄為/data/wwwsite/howtocn.org/www/http://nginx.howtocn.org時為/data/wwwsite/howtocn.org/nginx/,以此類推。

後面if語句的作用是將howtocn.org的方位重定向到http://www.howtocn.org,這樣既解決了網站的主目錄訪問,又可以增加seo中對http://www.howtocn.org的域名權重。

3、多個正則表示式

如果你在server_name中用了正則,而下面的location欄位又使用了正則匹配,這樣將無法使用2這樣的引用,解決方法是通過set指令將其賦值給一個命名的變數:

server
   {
     listen      80;
     server_name ~^(.+)?\.howtocn\.org$;
     set $www_root $1;
     root /data/wwwsite/howtocn.org/$www_root/;
     location ~ .*\.php?$ {
         fastcgi_pass   127.0.0.1:9000;
         fastcgi_index  index.php;
         fastcgi_param  SCRIPT_FILENAME /data/wwwsite/howtocn.org/$fastcgi_script_name;
         include        fastcgi_params;
         }
   }

三、參考資料

原文連結:http://mp.weixin.qq.com/s?__biz=MzI3MTI2NzkxMA==&mid=2247484473&idx=1&sn=31dec469640f5ffd9f54badcef47770d&scene=1&srcid=0912ElpbLsGU0NxIk2ZB6TIn#rd