Where to put map in Nginx configs/templates?

I want to block bad bots (any visitor with user agent below 14 symbols length). So I tried to modify default Nginx template for the site adding right at the top of .tpl and .stpl code before server line:

map $http_user_agent $blocked {
	~*^.{0,13}$ 1;
	default 0;
}

And inside server before the first location I put this:

	if ($blocked) {
		return 403;
	}

I made a copy of the template, added it to my domain via panel and rebuild the user. But it doesn’t work :(. I can see 200 OK for visitors without User Agent or with short ones in logs.

Is it OK to use map like this in .tpl or should I put it into nginx.conf directly?

If you define map directive outside server block, the directive will be global so there is no need to add it to .stpl, indeed I won’t use it in a template, I would define it on for example /etc/nginx/conf.d/maps.conf

Also, you should surround the regex with double quotes or it will fail:

map $http_user_agent $blocked {
	"~*^.{0,13}$" 1;
	default 0;
}

The if block should be added to both templates, .tpl and .stpl.

1 Like

Thanks, will try this way.

1 Like