Rootop 服务器运维与web架构

nginx if多条件判断的实现

if判断本身不支持多条件判断,用不了 && 或者|| 这种逻辑运算,而且if也不支持嵌套。
可以通过set变量来迂回实现。

比如这里我要实现访问a.rootop.org跳转到匹配子域名到指定的html页面。
dns和nginx已经配置了泛域名

实现效果:
a.rootop.org -> rootop.org/pages/a.html
b.rootop.org -> rootop.org/pages/b.html

但是这里要排除www.rootop.org的跳转

server
{
	listen 80;
	server_name rootop.org www.rootop.org *.rootop.org;
	root html;
	
	# 子域名跳转指定html页面
	# 先设置个变量
	set $subdomain "";
	
	# 正则获取三级域(也就是主机名)
	if ($http_host ~* "^(.*)\.rootop\.org$")
	{
		set $subdomain $1;
	}

	# 排除www
	if ($subdomain = "www")
	{
		set $subdomain "";
	}

	# 除www外的实现跳转
	if ($subdomain != "")
	{
		# 注意加上$scheme,如果是rootop.org/pages/xxx.html,则会认为是在域名后面加了个目录地址。
		return 301 $scheme://rootop.org/pages/$subdomain.html;
	}
}

如果想反过来实现也可以

# html页面跳转子域名
if ($uri ~* ".*/pages/(.*)\.html")
{
	return 301 $scheme://$1.rootop.org;
}

原创文章,转载请注明。本文链接地址: https://www.rootop.org/pages/4644.html

作者:Venus

服务器运维与性能优化

评论已关闭。