Nginx二级域名自动匹配到子文件夹(通过rewrite)

server_name www.test.com bbs.test.com blog.test.com;
index index.html index.htm index.php;
root /www/test.com;



#申明sub_domain变量
set $sub_domain "";
#正则提取出二级域名
if ($http_host ~ "(.+).test.com$") {
    #把二级域名赋值给sub_domain变量
    set $sub_domain $1;
}

if ($sub_domain = "www") {
    set $sub_domain "";
}

if ($sub_domain = "bbs") {
    rewrite /(.+) /$sub_domain/$1 last;
}

if ($sub_domain = "blog") {
    #设置rewrite规则
    rewrite ^(.*)$ /$sub_domain/index.php?s=$1 last;
}