8

I'm trying to log only java-script files request in the nginx access_log. I tried using the following code i found on this site:

location ~* ^.+.(jpg|jpeg|gif|css|png|html|htm|ico|xml|svg)$ {
   access_log        off;
}

the problem is it doesn't allow the get request at all and i get a 404 error when trying to run the html file that executes the js file in the browse.

I want everything to work just the same but for the access log to log only request for js files. How do i do that?

alex
  • 8,904
  • 6
  • 49
  • 75
michael
  • 81
  • 1
  • 3

2 Answers2

15

Put it in the server block and make sure that the "root" is correctly set up. It does work

Working example:

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires    +60d;
    access_log off;
}

I have this in the server block and not a location block.

alex
  • 8,904
  • 6
  • 49
  • 75
Olafur Tryggvason
  • 4,761
  • 24
  • 30
  • 2
    i did as you suggested: server { listen 80; server_name X.XXX.XXX.XX; location / { root html/run; index index.html index.htm; } location ~* \.(css|png|jpg|jpeg|gif|ico|html)$ { access_log off; } } but it prevents access to the files all together. what am i doing wrong? – michael Dec 04 '14 at 12:39
  • Did you mean leaving it empty like that: location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { } ? It didn't work this way. the pages were not loaded (404) – michael Dec 04 '14 at 14:17
  • No, just take it away completely. Just trying to figure out where the problem is. Can you view images if you take it away and reload nginx. – Olafur Tryggvason Dec 04 '14 at 14:19
  • 1
    Yes i can. it was the original set up – michael Dec 04 '14 at 14:20
1

Alternatively you can keep all requests within single location but use access_log with condidional if operator to disable images logging:

map $request_uri $is_loggable {
    ~* ^.+\.(jpg|jpeg|gif|css|png|html|htm|ico|xml|svg)$ 0;
    default                                             1;
}
server {
    location / {
        access_log /path/to/log/file combined if=$is_loggable;
        ...
    }
}

Here combined is a name of default log format.

You say that you want to log only java-script files, so actually you can use even simplier solution:

map $request_uri $is_loggable {
    ~* ^.+\.js$  1;
    default      0;
}
Marat Safin
  • 1,793
  • 20
  • 28
  • didnt work for me, nginx syntax error : nginx: [emerg] invalid number of the map parameters – AWS PS Aug 10 '22 at 06:27
  • Just need to adjust the map by quoting the first parameter: `map $request_uri $is_loggable { default 1; '~*^.+\.(jpg|jpeg|gif|css|png|html|htm|ico|xml|svg|js|map|woff|woff2)$' 0; }` – Marlon Anjos Mar 29 '23 at 19:58