I have a running website where I have a specific directory where I store random stuff (it sounds very informal and it indeed is).
So, I wanted to have some sort of index there that lists the contents of that directory (and subdirectories). autoindex
would work perfectly.
Then, I don't really want others to browse that index. auth_basic
would work perfectly.
But, I'd like to be able to link to specific files or directories inside that directory (that is a directory that does contain an index file and not an autoindex) without having them password protected.
So, the final idea would be to have a location with autoindices that are password protected with basic auth but leaving the rest of the files and directories untouched.
I came up with a hacky solution that works: since an HTTP status 403 is issued when an index that does not exist is accessed, I redirect that to a custom location
block that enables autoindex
with auth_basic
.
See here an example:
server {
root ...;
index index.php index.html index.htm;
server_name ...;
access_log ...;
error_log ...;
# general site
location / {
try_files $uri $uri/ @rewrite;
location ~ \.php(/|$) {
include fastcgi.conf;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
try_files $uri $uri/;
fastcgi_pass unix:/run/php/php-fpm-....sock;
}
}
# rewrite for the general site
/location @rewrite {
rewrite ...;
}
# that specific directory
location /directory {
try_files $uri $uri/ =404;
error_page 403 = @autoindex; # hack 1
location ~ \.php(/|$) {
# include snippets/fastcgi-php.conf;
include fastcgi.conf;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
try_files $uri $uri/;
fastcgi_pass unix:/run/php/php-fpm-....sock;
}
}
# password-protected autoindices
location @autoindex {
autoindex on;
autoindex_exact_size off;
auth_basic "directory";
auth_basic_user_file /.../.htpasswd;
}
}
So... is there a better idea? Is this hack a bad idea?
Thank you!