Once I needed to additionally keep a log of 404 requests in a separate file, with subsequent export via rsyslog to a mysql database and processing by scripts.
Let me give an example of registering requests with code 4xx and 404:
map $status $loggable {
~^[4] 1;
default 0;
}
map $status $loggable {
~^[404] 1;
default 0;
}
Then we will indicate where to save the logs of such requests:
access_log /var/log/nginx/ixnfo.com_404.log combined if=$loggable;
If the configuration already has access_log /var/log/nginx/access.log for example, then all access logs will still be written to it, and only those with code 404 will be written to 404.log.
map should be specified not in the server directive, but for example before it, and access_log in the server of the desired server, for example:
map $status $loggable {
~^[4] 1;
default 0;
}
server {
listen 443
access_log /var/log/nginx/ixnfo.com_access.log;
error_log /var/log/nginx/ixnfo.com_error.log;
access_log /var/log/nginx/ixnfo.com_4xx.log combined if=$loggable;
...
Also map can be used with GeoIP:
apt install libnginx-mod-http-geoip geoip-database
nano /etc/nginx/conf.d/geoip.conf
map $geoip_country_code $allowed_country {
default no;
UA yes;
US yes;
server {
listen 443
# ru.wikipedia.org/wiki/ISO_3166-1
if ($allowed_country = no) {
return 444;
}
You can also perform a redirect:
map $request_uri $new_uri {
/old-url /new-url;
/old.html /new.html;
}
server {
listen 443
...
if ($new_uri) {
return 301 $new_uri;
}
Let’s check the correctness of the configuration and apply it:
nginx -t
service nginx restart
service nginx status
See my other articles about Nginx