Fix Permision Cho Folder WordPress Trên Synology Với User Http:Http

Nhớ chạy dưới quyền “sudo -i”

File này chạy cho folder “/volume1/web/nbhome/”

#!/bin/bash
set -euo pipefail

# === CẤU HÌNH ===
WEBROOT="/volume1/web/nbhome"

# Thử đoán user/group web trên Synology
WS_USER=""
for u in http nginx www-data apache; do
  if id "$u" >/dev/null 2>&1; then WS_USER="$u"; break; fi
done
WS_USER="${WS_USER:-http}"
WS_GROUP="$WS_USER"

echo "Using web server user/group: ${WS_USER}:${WS_GROUP}"
echo "Target root: ${WEBROOT}"
read -p "Tiếp tục? (y/N) " yn
[[ "${yn:-N}" =~ ^[Yy]$ ]] || { echo "Hủy."; exit 1; }

# 1) Chuyển quyền sở hữu toàn bộ site về user/group web
chown -R "${WS_USER}:${WS_GROUP}" "$WEBROOT"

# 2) CHMOD mặc định: thư mục 755, file 644
find "$WEBROOT" -type d -not -path "*/\.git/*" -exec chmod 755 {} \;
find "$WEBROOT" -type f -not -path "*/\.git/*" -exec chmod 644 {} \;

# 3) Tăng quyền ghi cho khu vực WordPress cần ghi (wp-content)
if [ -d "$WEBROOT/wp-content" ]; then
  chmod 775 "$WEBROOT/wp-content"
  find "$WEBROOT/wp-content" -type d -exec chmod 775 {} \;
  find "$WEBROOT/wp-content" -type f -exec chmod 664 {} \;

  # setgid để thư mục con kế thừa group (giữ ${WS_GROUP})
  find "$WEBROOT/wp-content" -type d -exec chmod g+s {} \;
fi

# 4) Bảo vệ file nhạy cảm
[ -f "$WEBROOT/wp-config.php" ] && chmod 640 "$WEBROOT/wp-config.php"
[ -f "$WEBROOT/.htaccess" ] && chmod 644 "$WEBROOT/.htaccess"
[ -f "$WEBROOT/nginx.conf" ] && chmod 644 "$WEBROOT/nginx.conf"

# 5) (Tuỳ chọn) cấp quyền ghi cho các thư mục thường được plugin dùng
for d in uploads cache upgrade languages; do
  if [ -d "$WEBROOT/wp-content/$d" ]; then
    chmod 775 "$WEBROOT/wp-content/$d"
    find "$WEBROOT/wp-content/$d" -type d -exec chmod 775 {} \;
    find "$WEBROOT/wp-content/$d" -type f -exec chmod 664 {} \;
  fi
done

# 6) (Tuỳ chọn) nếu dùng WP-CLI trong cron với user khác, cho phép group ghi root site
# chmod 775 "$WEBROOT"
# find "$WEBROOT" -maxdepth 1 -type f -name "*.php" -exec chmod 664 {} \;

echo "Hoàn tất. Kiểm tra lại quyền và thử cập nhật plugin/theme trong WP."