Log only certain file types being downloaded from your website with nginx access_log directive

Hosting

Say you host a website where you have workshops in PDF and would like to get statistics on how many people download them, but due to the setup of your CMS (in my case Drupal) and links being already on the website it is almost impossible. Luckily, those of you who use Nginx as their web server can configure it to log only certain file types being downloaded.

Here is how

Say this is your default config file:

server {
        listen   80;
        server_name  www.cookiesandcream.com cookiesandcream.com www.cookiesandcream.net cookiesandcream.net doct$

        location / {
                root   /var/www/drupal;
                index  index.php index.html index.htm;
                client_max_body_size 4M;
                client_body_buffer_size 128k;
        if (!-e $request_filename) {
                rewrite  ^/(.*)$  /index.php?q=$1  last;
                break;
            }
        }

        location ~ \.php$ {
            fastcgi_pass   unix:/usr/local/var/run/php-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /var/www/drupal$fastcgi_script_name;
            include        fastcgi_params;
        }
}

and we want only PDFs and PPTs being tracked in the log file. So we add this piece:

        location ~* ^.+.(pdf|ppt)$ {
                access_log /var/log/nginx/pdf_ppt.downloads.log combined;
                root   /var/www/drupal;
        }

Finally, our config file now looks like this:

server {
        listen   80;
        server_name  www.cookiesandcream.com cookiesandcream.com www.cookiesandcream.net cookiesandcream.net doct$
         location ~* ^.+.(pdf|ppt)$ {
                access_log /var/log/nginx/pdf_ppt.downloads.log combined;
                root   /var/www/drupal;
        }
        location / {
                root   /var/www/drupal;
                index  index.php index.html index.htm;
                client_max_body_size 4M;
                client_body_buffer_size 128k;
        if (!-e $request_filename) {
                rewrite  ^/(.*)$  /index.php?q=$1  last;
                break;
            }
        }

        location ~ \.php$ {
            fastcgi_pass   unix:/usr/local/var/run/php-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /var/www/drupal$fastcgi_script_name;
            include        fastcgi_params;
        }
}

That was easy, right?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.