Anonymize IP addresses in NGINX log files



In an attempt to piggyback on the people's vague fear of random lawsuits in Germany, I'll blog on how to remove the last octet of an IP in NGINX log files. You first have to define a log format and then use it wherever you see fit. To define the log format, you use the log_format directive. This directive - according to the manual - is only allowed in http context. So for an NGINX default setup, you can put the following in your /etc/nginx/nginx.conf within the curly brackets of http:
map $remote_addr $ip_anonym1 {
    default 0.0.0;
    "~(?P<ip>(\d+)\.(\d+)\.(\d+))\.\d+" $ip;
    "~(?P<ip>[^:]+:[^:]+):" $ip;
}

map $remote_addr $ip_anonym2 {
    default .0;
    "~(?P<ip>(\d+)\.(\d+)\.(\d+))\.\d+" .0;
    "~(?P<ip>[^:]+:[^:]+):" ::;
}

map $ip_anonym1$ip_anonym2 $ip_anonymized {
    default 0.0.0.0;
    "~(?P<ip>.*)" $ip;
}

log_format anonymized '$ip_anonymized - $remote_user [$time_local] '
    '"$request" $status $body_bytes_sent '
    '"$http_referer" "$http_user_agent"';
**Important** (mentioning it, mainly because I fell for it): Make sure that you put it *before* the line include /etc/nginx/sites-enabled/*;. From now on you can specify this log format in the end of every access_log directive.
access_log /var/log/nginx/www.google.com_access.log anonymized;
Some random thoughts to conclude this blag post: I'm with [XKCD](https://xkcd.com/1998/) on this one. People are going crazy about DS-GVO. And imho the new regulation are not meant for John Doe who is hosting his blog with three visitors a week. No Public Authority (TM) will go after him. There still is the fear of rogue lawyers roaming the Internet to do something that one could call *Abmahnung mit Vergleichsangebot*, of course. Such a thing feels a lot like a formalized (and legal!) blackmail: you get a "you are doing something wrong and I'm going to sue you, but you can give me money and I'll not do that"-letter. But when you do stuff (with your life) this can happen all the time! So you decide: curl up in a ball of fur with no Internet access or tell those damn lawyers to bring it on?!

Tags: - - - - - -

Leave a Reply

Your email address will not be published.