# ----------------------------------------
# Security Rules (No performance impact)
# - System file protection
# - Query filtering
# - PHP execution control
# ----------------------------------------

# Disable directory listing
Options -Indexes +FollowSymLinks

# Protect critical WordPress files
<FilesMatch "^(wp-config\.php|php\.ini|web\.config|readme\.html|license\.txt|\.htaccess|\.htpasswd|\.env|debug\.log|error_log)$">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
    <IfModule !mod_authz_core.c>
        Order deny,allow
        Deny from all
    </IfModule>
</FilesMatch>

# Block sensitive file access
<FilesMatch "\.(log|sql|bak|old|orig|config|ini|db)$">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
    <IfModule !mod_authz_core.c>
        Order deny,allow
        Deny from all
    </IfModule>
</FilesMatch>

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Protect core WordPress files
    RewriteRule ^wp-includes/.*\.php$ - [F,L]
    RewriteRule ^wp-admin/includes/.*\.php$ - [F,L]

    # Block PHP execution in uploads
    RewriteRule ^wp-content/uploads/.*\.(php|phar|phtml|php[3-7]|pht|phps|phtm|sh|pl|py|jsp|asp|aspx|cgi|exe|dll)$ - [F,L]

    # Critical SQL Injection Protection
    RewriteCond %{QUERY_STRING} (?i)(union.*select|drop.*table|information_schema) [NC,OR]
    RewriteCond %{QUERY_STRING} (?i)(exec\s*\(|system\s*\(|shell_exec\s*\() [NC,OR]
    RewriteCond %{QUERY_STRING} (?i)(/etc/passwd|wp-config\.php|\.htaccess) [NC,OR]
    RewriteCond %{QUERY_STRING} (?i)(\.\.%2f|%2e%2e%2f|%252e%252e) [NC]
    RewriteRule .* - [F,L]

    # Block XSS patterns
    RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
    RewriteCond %{QUERY_STRING} (javascript:|onload=|onerror=) [NC]
    RewriteRule .* - [F,L]

    # Block dangerous HTTP methods
    RewriteCond %{REQUEST_METHOD} ^(TRACE|DELETE|TRACK) [NC]
    RewriteRule .* - [F,L]

    # Block common malicious scanners
    RewriteCond %{HTTP_USER_AGENT} ^.*(sqlmap|acunetix|nikto|wpscan).* [NC]
    RewriteRule .* - [F,L]    

    # Prevent username enumeration
    RewriteCond %{REQUEST_URI} !^/wp-admin [NC]
    RewriteCond %{QUERY_STRING} author=\d+ [NC]
    RewriteRule .* - [F,L]
</IfModule>