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

Sorry to bump this, but can this query be used in .htaccess file or the robots.txt file as well, to block the bots?

In .htaccess you could try this (I didn’t test it, I don’t use Apache):

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^.{0,13}$ [NC]
RewriteRule ^.*$ - [F,L]
2 Likes

Thanks. Let me try that.
BTW, how would one run websites and servers without apache and nginx? I thought one cannot have public websites without these 2.

1 Like

You don’t have to run Apache AND nginx in HestiaCP. There is an nginx only option.

1 Like

no no. Let me rephrase. I meant, one needs to have either apache or nginx to run, right? Apologies, if this question sounds naive or stupid, but I have seen many write, I do not use nginx, or I do not use apache, etc. So, I am in general confused. Hence this question.

There Is also litehttp caddy and so on but you need a webserver for it (And these are not supported with Hestia)

2 Likes