Michał Kowol Tech Blog

How to server cifi shared folder using nginx.

Setup

Create folder /media/storage/dir/

mkdir -p /media/storage/dir/

Next, mount shared directory. uid and gid are very important because without this you will get 403 Forbidden.

sudo mount -t cifs -o uid=www-data,gid=www-data,ro,username=username,password=password //10.0.0.2/shared/ /media/storage/dir/
  • -t cifs - type of fs (cifs - Common Internet File System, also known as smb)
  • uid - specific user
  • gid - specific groutp
  • ro - read-only
  • rw - read-write
  • username - shared directory username
  • password - shared directory password

Modify nginx config (/etc/nginx/sites-available/somefile)

#...
server {
  location / { 
    alias /media/storage/dir/;
    autoindex on;
    autoindex_localtime on;
    autoindex_exact_size off;
  }
}

Password protecion

Add user bob to .htpasswd file using this command:

sudo sh -c "echo -n 'bob:' >> /etc/nginx/.htpasswd"

Add an encrypted password for the username:

sudo sh -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd"

Remember to set correct permissions:

sudo chown www-data:www-data /etc/nginx/.htpasswd
sudo chown 600 /etc/nginx/.htpasswd

Add this to ngnix config:

#...
server {
  location / { 
    alias /media/storage/dir/;
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime on;
    auth_basic "Restricted Content";
    auth_basic_user_file /etc/nginx/.htpasswd;
    # disable_symlinks off; # ???
  }
}

Autoindex for all locations in given section

#...
server {
  
  autoindex on;
  autoindex_localtime on;
  autoindex_exact_size off;

  location / { 
    alias /media/storage/;
  }

  location /foo { 
    alias /media/storage/foo;
  }

  location /bar { 
    alias /media/storage/test;
  }
}