Nginx – Redirect Tor Exit Node IP List to Special Page

nginxredirecttor

I download every 30 minutes the Tor exit node list https://www.dan.me.uk/torlist/ and save it to tor-ip.conf file.

My hoster does not allow to install any modules for nginx so I have to use what I have.

I thought to include the file into a variable and call redirect it if it should match.

nginx.conf

$bad_user {
    include /var/www/vhosts/domain/tor-ip.conf;
}

if ($bad_user) {
    rewrite ^ http://www.google.com;
}

tor-ip.conf

1.41.177.72
1.42.47.215
100.0.53.178
100.15.114.155
100.16.220.246
100.34.251.120
100.36.123.111
100.6.14.127
100.7.25.216
101.100.144.174
101.175.68.120
101.176.45.79
...

Nginx does not allow me to use the variable directly as $bad_user.
How could I set it?

Best Answer

A more easy approach to block Tor users is to use the deny directive within nginx. You can create a list of deny entries based on the torlist and include it in your nginx config.

How does your cronjob to pull the tor-ip.conf work? In case you can execute some shell commands you may do something similar to this Gist tiagoad/block-tor.sh

wget -qO- https://check.torproject.org/exit-addresses | grep ExitAddress | cut -d ' ' -f 2 | sed "s/^/deny /g; s/$/;/g" > blacklist.conf

In nginx you then just include the blacklist.

include blacklist.conf;

The file contains statements like this:

deny    100.0.53.178;
deny    100.15.114;
...

You need to reload nginx each time the blacklist changes.

If you want to redirect to a special page. You can try to utilize the error_page directive in combination with the deny directive.

location / {
    error_page 403 = @blacklisted;
    include blacklist.conf;
}
location @blacklisted {
    allow all;
    return 301 https://www.google.com;
}

Maybe more easy even like this:

location / {
    error_page 403 =301 https://www.google.com;
    include blacklist.conf;
}