To streamline the permission-setting process, especially for future deployments or when setting up multiple environments, consider using a Bash script.
Sample Script: set_
permissions.sh
bashCopy code#!/bin/bash
# Variables
LARAVEL_DIR="/var/www/html/example" # Replace with your Laravel project path
WEB_USER="www-data" # Replace with your web server user (e.g., www-data, nginx)
# Function to display messages
function echo_info() {
echo -e "\e[32m[INFO]\e[0m $1"
}
function echo_error() {
echo -e "\e[31m[ERROR]\e[0m $1"
}
# Check if Laravel directory exists
if [ ! -d "$LARAVEL_DIR" ]; then
echo_error "Laravel directory '$LARAVEL_DIR' does not exist."
exit 1
fi
# Navigate to Laravel directory
cd "$LARAVEL_DIR" || { echo_error "Cannot navigate to Laravel directory."; exit 1; }
echo_info "Setting ownership to $WEB_USER:$WEB_USER for $LARAVEL_DIR"
# Set ownership to web server user and group
sudo chown -R "$WEB_USER":"$WEB_USER" "$LARAVEL_DIR"
echo_info "Setting directory permissions to 755"
# Set directory permissions to 755
sudo find storage bootstrap/cache public/uploads -type d -exec chmod 755 {} \;
echo_info "Setting file permissions to 644"
# Set file permissions to 644
sudo find storage bootstrap/cache public/uploads -type f -exec chmod 644 {} \;
echo_info "Setting writable permissions for storage, bootstrap/cache, and public/uploads directories to 775"
# Set writable permissions for storage, bootstrap/cache, and public/uploads
sudo chmod -R 775 storage bootstrap/cache public/uploads
echo_info "Creating laravel.log if it doesn't exist and setting permissions"
# Create laravel.log if it doesn't exist
if [ ! -f storage/logs/laravel.log ]; then
sudo touch storage/logs/laravel.log
sudo chown "$WEB_USER":"$WEB_USER" storage/logs/laravel.log
fi
# Set permissions for laravel.log
sudo chmod 664 storage/logs/laravel.log
# (Optional) Set ACLs for more granular permissions
echo_info "Setting ACLs for storage, bootstrap/cache, and public/uploads directories"
# Check if ACL is installed
if dpkg -s acl &> /dev/null; then
sudo setfacl -R -m u:"$WEB_USER":rwx storage bootstrap/cache public/uploads
sudo setfacl -dR -m u:"$WEB_USER":rwx storage bootstrap/cache public/uploads
echo_info "ACLs have been set successfully."
else
echo_info "ACL package not installed. Skipping ACL configuration."
echo_info "To install ACL, run: sudo apt install acl"
fi
echo_info "Permissions have been set successfully."
How to Use the Script:
Create the Script File:
nano set_permissions.sh
Paste the Script Content: Copy the script above into the
set_
permissions.sh
file.Make the Script Executable:
chmod +x set_permissions.sh
Run the Script:
./set_permissions.sh
You may be prompted to enter your password for
sudo
commands.