Sharing confidential data with nginx and htaccess
Have I mentioned I love my Virtual Private Server? It’s 10€ per month and I discover new uses for it almost every week.
Today, I found yet another use for it: Sharing large and confidential files with your client.
My VPS has the nginx webserver running. My goal was to have one password-protected folder per company where I can upload files that only they can then see. I found this tutorial I could just follow with small adaptations. And here is how I did it:
-
Install the package that brings the ‘htpasswd’ tool to you. In Arch Linux, this was “apache-tools”. You can do this on your local machine or on the server, as you only need it to generate a line containing a hashed password.
Then, create a line in a new htpasswd file as such:
htpasswd -c ~/temp/myhtaccess companyA
This prompts you for a password, and then creates a htpasswd file at your specified path for the user ‘companyA’.
-
Now, ssh on your VPS. Open a new (or existing) htpasswd file somewhere. The tutorial I followed used
/etc/nginx/htpasswd
. But since I require several directories, each with their own user, I will create one htpasswd file per company:# This is /etc/nginx/htpasswd_companyA companyA:$apr1$k0HceFoe$zS3LUdUJAuGh922jbmZjF0
This is the user name and the encrypted password (a dummy password here, of course).
-
Now, create a
files/
folder, and a subfolder for company A:mkdir -p /var/www/html/files/companyA
You will want to change the group ownership of
/var/www/html/files/companyA
towww-data
, and add your remote user to that group, so that uploading works:sudo chgrp -R /var/www/html/www-data files sudo chmod -R g+w /var/www/html/files
-
Tell nginx to password protect this folder:
# Use your favorite editor to edit this file: sudo emacs /etc/nginx/sites-enabled/default
You will add a new
location
entry. The file should then look like this (comments removed for readability):server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name _; location / { try_files $uri $uri/ =404; } location /files/companyA { auth_basic "Restricted Content!"; auth_basic_user_file /etc/nginx/htpasswd_companyA; } }
-
Restart nginx:
sudo service nginx restart
-
Upload your confidential data, now from your local machine:
scp secret_stuff.zip vps:/var/www/html/files/companyA/
And then test downloading it from your browser. Enter your server URL, followed by
files/companyA/secret_stuff.zip
. You should see a user/password form, and only be able to download the data when your user and password are correct.