We wanted a counter that counts the visitors IP from access.log as it’s more accurate than some web counter. And finally we found a really simple command to count unique IP addresses from access.log in Apache. As we found it useful, we thought we’d post it.
What it does is that it counts all the IP addresses that has visited your server. It sorts it and puts it in a log file.
-
Go to the folder where you have your access.log
Apache:
$~: cd /var/log/apache
Nginx:
$~: cd /var/log/nginx
-
Write this command in that folder
$~: awk '{print $1}' access.log*|sort|uniq -c|sort -n >> all_uniqe_ip.log
If you want the total amount of unique visitors based on the IP, including bots – you would use this instead:
$~: awk '{print $1}' access.log*|sort|uniq|wc -l
-
Show the file
$~: nano all_uniqe_ip.log
-
Make a script
If you want the system to count the visitors every day you can make a script out of it and put that script in a cronjob
$~: sudo nano /var/log/your-system/all_uniqe_ip.sh
Put this in:
#!/bin/bash awk '{print $1}' /var/log/your-system/access.log*|sort|uniq -c|sort -n >> all_uniqe_ip.log exit 0
Save with [CTRL+X] and then press [ENTER]
-
Make a cronjob
$~: sudo -i
$~: crontab -e
Put this in the crontab file:
@daily /var/log/your-system/all-ip.sh
That’s all!