SJT
SJT

Reputation: 1097

Nginx: password protect folder except index page

A folder in my site is protected by password. It contains a subsite: example.com/subsite. I want to expose (remove password protection) for just the subsite home page, so anyone can browse to example.com/subsite and get /subsite/index.html, but any other page in the folder still requires credentials.

The authentication already works:

location /subsite {
  auth_basic "Subsite users only.";
  auth_basic_user_file /etc/nginx/subsite-pwds;
}

I can expose the home page, which needs some other resources to work.

# public access to home page only
location = /subsite/index.html {
    auth_basic off;
}
location /subsite/assets {
    auth_basic off;
}
location /subsite/img {
    auth_basic off;
}
location /subsite/scripts {
    auth_basic off;
}
location /subsite/stylesheets {
    auth_basic off;
}

This allows anyone to fetch example.com/subsite/index.html. But what I want is for anyone to be able to fetch example.com/subsite.

None of the following alternatives to the first location block above has worked. All produce password challenges to example.com/subsite

# 1
location = /subsite {
    auth_basic off;
}
# 2
location = /subsite/ {
    auth_basic off;
}
# 3
location = /subsite {
    auth_basic off;
    rewrite ^ /subsite/index.html last;
}
# 4
location ~ ^/subsite$ {
    auth_basic off;
}

Upvotes: 1

Views: 771

Answers (1)

Richard Smith
Richard Smith

Reputation: 49672

Based on the default behaviour of Nginx, the URI /subsite (which resolves to a directory), is externally redirected to /subsite/.

The URI /subsite/ is internally redirected to /subsite/index.html by the index module.

Each of these URIs, /subsite, /subsite/ and /subsite/index.html, are processed separately, and any of them can trigger an authentication check if Nginx chooses your location /subsite { ... } block to process the individual URI.

To bypass your authentication check for the index page, you will need one or more locations matching the three URIs in addition to the resource URIs identified in your questions.

For example:

location = /subsite {
    auth_basic off;
}
location = /subsite/ {
    auth_basic off;
}
location = /subsite/index.html {
    auth_basic off;
}
location /subsite/assets {
    auth_basic off;
}
location /subsite/img {
    auth_basic off;
}
location /subsite/scripts {
    auth_basic off;
}
location /subsite/stylesheets {
    auth_basic off;
}

Upvotes: 1

Related Questions