What Permission To Set For User File Upload Directory (Web Folder)

TLDR:


sudo chmod u=rwX,g=rwXs,o=rX -R path/to/folder
sudo chown www-data:www-data path/to/folder
sudo adduser username www-data

Introduction

If you've ever ran into a problem where your web app/server (Apache or NGINX) cannot read or write from a web folder (user upload directory), it's probably because of the file permissions. Unfortunately most people recommend setting it to 777, giving full access to everyone. Even some of the top answers on Stackoverflow recommend this. Let's see why this is a bad idea, and what's the correct way.

The Problem

To see why 777 is dangerous, we need to understand what's happening. It's giving read, write and execute access to owner, group and public! Let's imagine a common scenario. You have a PHP app that lets user upload to http://website.com/uploads/their-file. They upload a PHP file, virus.php, to http://website.com/uploads/virus.php. They visit that page… You're dead, because you've given execute access.

The Solution

u=rwX,g=rwXs,o=rX

I'm assuming you're familiar with chmod format. There are 2 letters which you might not be familiar with. X with a capital, means give execute access to directories, but not to files. This allows you to perform ls, but will not let you execute any script or program. s is a sticky bit that causes new directories inside to have the same owner. Useful when creating a new directory under a different user e.g. cron or ssh. In this case, we want new directories to belong to www-data group so that NGINX can access those files even if it was created by other users.

And of course remember to add your user to www-data group so that you will be able to access them through ssh or cron.

Keywords: permission, web, file, folder, directory, upload, linux, chmod, chown
Avatar

Contact