Protect /analytics on Nginx with basic authentication, but allow access to .php and .js files??

Francis Daly francis at
Wed Feb 11 20:21:30 UTC 2015

On Wed, Feb 11, 2015 at 11:45:46AM -0500, lmm5247 wrote:

Hi there,

> I have Piwik setup and running on a Nginx webserver that I protected with
> HTTP basic authentication, as seen below.
> location /analytics {
> alias /var/www/piwik/;
> auth_basic "Restricted";
> auth_basic_user_file /etc/nginx/pass;
> try_files $uri $uri/ /index.php;
> }

> I have it protected, but it's prompting to login on every page, due to the
> piwik.php and piwik.js files (necessary for analytics) being in my protected
> directory. This is described on Piwik's website, below.

What actual requests are made that are challenged for
authentication? Check your access_log for http 401.

At a guess, it is just /analytics/piwik.js that you care about here.

So: add

  location = /analytics/piwik.js {auth_basic off;}

inside your "location /analytics {}" block.

(This will try to serve the file "/var/www/piwik//piwik.js", given the
above configuration.)

> My question is: what kind of Nginx rule can I use to protect all files in
> that directory, besides those two? Is it possible to do a negative regex
> match on a location block?

It is usually simpler to use positive matching. The nginx "location"
rules usually let it be possible.

Francis Daly        francis at

More information about the nginx mailing list