Tags
  1. openssl passwd -apr1 your_password
  2. echo 'your_username:hashed_password' >> /etc/nginx/.htpasswd
  3. chmod 640 /etc/nginx/.htpasswd
  4. chown root:www-data /etc/nginx/.htpasswd
  5. vim /etc/nginx/sites-available/
location / {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
}

script

#!/bin/zsh
# Script Version: 01
# Description: Prompt for username, generate password, hash it, and save to Nginx .htpasswd

# Set variables
# ========
HTPASSWD_FILE="/etc/nginx/.htpasswd"
USERNAME=""
PASSWORD=""
HASHED_PASSWORD=""

# Functions
# ========
generate_password() {
    # Generate a 16-character alphanumeric password using OpenSSL without additional tools
    PASSWORD=$(openssl rand -base64 12)
}

hash_password() {
    # Hash the generated password using OpenSSL
    HASHED_PASSWORD=$(openssl passwd -apr1 "$PASSWORD")
}

append_htpasswd() {
    # Append the username and hashed password to the htpasswd file
    echo "$USERNAME:$HASHED_PASSWORD" >> "$HTPASSWD_FILE"
}

set_permissions() {
    # Ensure proper permissions and ownership of the htpasswd file
    if [ ! -f "$HTPASSWD_FILE" ] || [ $(stat -c "%a" "$HTPASSWD_FILE") -ne 640 ] || [ $(stat -c "%U:%G" "$HTPASSWD_FILE") != "root:www-data" ]; then
        chmod 640 "$HTPASSWD_FILE"
        chown root:www-data "$HTPASSWD_FILE"
    fi
}

# Main Process
# ========
# Prompt for the username
while true; do
    echo -n "Enter the username: "
    read USERNAME
    if [[ -z "$USERNAME" ]]; then
        echo "Username cannot be empty. Please enter a valid username."
    elif [[ ! "$USERNAME" =~ ^[a-zA-Z0-9_]+$ ]]; then
        echo "Username contains invalid characters. Only alphanumeric characters and underscores are allowed."
    else
        break
    fi
done

# Generate password
generate_password

# Hash the password
hash_password

# Append to htpasswd file
append_htpasswd

# Set proper permissions for the htpasswd file
set_permissions

# Show the generated password to the user
echo "Generated password for $USERNAME: $PASSWORD"

echo

echo 'Please add the following lines to your Nginx configuration file to enable authentication:'
echo 'auth_basic "Restricted Access";'
echo 'auth_basic_user_file /etc/nginx/.htpasswd;'