BASH

Set Secure Web Project File Permissions

Secure your web applications by correctly setting file and directory permissions in Bash, ensuring proper access for the web server while maintaining security.

#!/bin/bash

WEB_ROOT="/var/www/html/my_webapp"
WEB_USER="www-data" # Common web server user (e.g., Apache/Nginx)

if [ ! -d "$WEB_ROOT" ]; then
  echo "Error: Web root directory '$WEB_ROOT' does not exist."
  exit 1
fi

echo "Setting ownership for $WEB_ROOT to $WEB_USER:$WEB_USER..."
sudo chown -R $WEB_USER:$WEB_USER "$WEB_ROOT"

echo "Setting directory permissions to 755 (rwxr-xr-x)..."
sudo find "$WEB_ROOT" -type d -exec chmod 755 {} \;

echo "Setting file permissions to 644 (rw-r--r--)..."
sudo find "$WEB_ROOT" -type f -exec chmod 644 {} \;

echo "Permissions set successfully for $WEB_ROOT."
How it works: This script sets recommended secure file and directory permissions for a web project. It first changes the ownership of the entire `WEB_ROOT` directory and its contents to the specified `WEB_USER` (e.g., `www-data` for Apache/Nginx). Then, it sets all directories to `755` (read, write, execute for owner; read and execute for group and others) and all files to `644` (read and write for owner; read-only for group and others). This ensures the web server can access files, while preventing unauthorized modifications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs