现在的位置: 首页 > 综合 > 正文

Nginx配置二级子域名

2013年10月13日 ⁄ 综合 ⁄ 共 1122字 ⁄ 字号 评论关闭

准备:需要泛域名 domain.com。

主机:www.domain.com 或 domain.com。

思路:将*.domain.com 解析到主机www.domain.com/*/ (*不能为www或空)。

配置:

if ( $host ~* (\b(?!www\b)\w+)\.\w+\.\w+ ) {
	set $subdomain $1;
}

location / {
	root   D:\www\domain.com\$subdomain;
	index  index.html index.htm;
}

 

测试

环境:Window7 + Nginx1.1.15

ToDo:

1、安装Nginx至:D:\nginx-1.1.15;安装后路径

2、修改nginx配置文件,见上;

3、新建web应用目录:D:\www\;

4、新建domain.com项目目录:D:\www\domain.com\;使用tree命令打印项目目录部署如下:

D:\WWW
└─domain.com
    │  index.html (Welcome to www.domain.com!)
    ├─a
    │      index.html (www.domain.com/a/index.html)
    │      test.html (www.domain.com/test.html)
    ├─b
    │      index.html (www.domain.com/b/index.html)

5、修改hosts文件:C:\Windows\System32\drivers\etc\hosts,新增如下行:

127.0.0.1	www.domain.com
127.0.0.1	domain.com
127.0.0.1	a.domain.com

6、启动nginx。

用例

访问:http://www.domain.com/结果:Welcome to www.domain.com!
访问:http://domain.com/ 结果:Welcome to www.domain.com!
访问:http://a.domain.com/ 结果:www.domain.com/a/index.html
结果:http://a.domain.com/test.html结果:www.domain.com/a/test.html

结果:与用例相同!

补充:

请求参数作为二级域名如何处理?
Re:采用urlrewrite或类似url重写的工具实现,步骤如下:
www.domain.com/shop.jsp?shop_key=suning
重写成:
www.domain.com/suning/
注:前提是shop_key唯一。

正则表达式参考网址:http://wangyan.org/blog/nginx-subdomain.html

抱歉!评论已关闭.