# ----------------------------------------------------------------------
# 1. FORCE HTTPS AND WWW/NON-WWW CONSISTENCY
# ----------------------------------------------------------------------
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Force HTTPS connections
    RewriteCond %{HTTPS} !=on
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
</IfModule>

# ----------------------------------------------------------------------
# 2. DISABLE DIRECTORY BROWSING (PREVENTS FILE SNOOPING)
# ----------------------------------------------------------------------
# Stops attackers from viewing your folder structures if an index.html is missing
Options -Indexes

# ----------------------------------------------------------------------
# 3. PROTECT SENSITIVE FILES AND THE HTACCESS FILE ITSELF
# ----------------------------------------------------------------------
# Prevent viewing of the .htaccess file and any .htpasswd credentials
<FilesMatch "^.*\.([Hh][Tt][AaPp])">
    Require all denied
</FilesMatch>

# Block common sensitive files (git directories, backup files, logs)
<FilesMatch "^(config\.json|package\.json|error_log|\.git|\.env)">
    Require all denied
</FilesMatch>

# ----------------------------------------------------------------------
# 4. INJECT ROBUST HTTP SECURITY HEADERS
# ----------------------------------------------------------------------
<IfModule mod_headers.c>
    # Prevent site from being embedded in iframes (Mitigates Clickjacking)
    Header set X-Frame-Options "SAMEORIGIN"

    # Block browsers from guessing MIME types away from what the server declares
    Header set X-Content-Type-Options "nosniff"

    # Enable strict browser cross-site scripting (XSS) filters
    Header set X-XSS-Protection "1; mode=block"

    # Enforce strict HTTPS for 1 year (HSTS) - Only use if SSL is fully active
    Header set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"

    # Control how much referrer information is shared with external links
    Header set Referrer-Policy "no-referrer-when-downgrade"

    # Basic Content Security Policy (CSP) - Restricts resources to your domain
    # Note: Adjust if using external scripts like Google Analytics or fonts
    Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;"
</IfModule>

# ----------------------------------------------------------------------
# 5. BLOCK BAD BOTS AND SPAMMERS (OPTIONAL)
# ----------------------------------------------------------------------
# Block specific known malicious IP addresses or bad user agents if needed
<Limit GET POST>
    # Example to block a specific malicious IP
    # Deny from 192.168.1.100
</Limit>