# ===================================================================
# UK Data Services - Enhanced Security .htaccess
# ===================================================================

# Enable RewriteEngine
RewriteEngine On

# ===================================================================
# 🔒 SECURITY HEADERS
# ===================================================================

<IfModule mod_headers.c>
    # Prevent MIME type sniffing
    Header always set X-Content-Type-Options "nosniff"
    
    # Prevent clickjacking
    Header always set X-Frame-Options "DENY"
    
    # Enable XSS filtering
    Header always set X-XSS-Protection "1; mode=block"
    
    # HSTS (HTTP Strict Transport Security) - Forces HTTPS
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
    
    # Referrer Policy
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    
    # Permissions Policy (formerly Feature Policy)
    Header always set Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()"
    
    # Content Security Policy (Enhanced)
    Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com https://www.google-analytics.com https://www.clarity.ms; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https://www.google-analytics.com; connect-src 'self' https://www.google-analytics.com https://analytics.google.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
    
    # Remove server signature
    Header unset Server
    Header unset X-Powered-By
    
    # Cache control for sensitive files
    <FilesMatch "\.(php|ini|log|sh|sql)$">
        Header set Cache-Control "no-cache, no-store, must-revalidate"
        Header set Pragma "no-cache"
        Header set Expires "0"
    </FilesMatch>
</IfModule>

# ===================================================================
# 🚫 BLOCK ACCESS TO SENSITIVE FILES
# ===================================================================

# Block access to sensitive files and directories
<FilesMatch "^(\.htaccess|\.htpasswd|\.env|\.git|\.svn|composer\.json|composer\.lock|package\.json|package-lock\.json)">
    Require all denied
</FilesMatch>

# Block access to specific file extensions
<FilesMatch "\.(ini|log|conf|sql|sh|bak|backup|old|tmp|temp|swp|swo|save)$">
    Require all denied
</FilesMatch>

# Block access to common backup and temporary files
<FilesMatch "(~|\.bak|\.backup|\.old|\.orig|\.save|\.swp|\.tmp|#)$">
    Require all denied
</FilesMatch>

# Block access to logs directory
<Directory "logs">
    Require all denied
</Directory>

# ===================================================================
# 🔐 DISABLE DANGEROUS PHP FUNCTIONS
# ===================================================================

<IfModule mod_php8.c>
    php_admin_value disable_functions "exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source,highlight_file"
</IfModule>

# ===================================================================
# 🚫 DIRECTORY SECURITY
# ===================================================================

# Disable directory browsing
Options -Indexes

# Disable server signature
ServerTokens Prod
ServerSignature Off

# Prevent access to .git directory
<DirectoryMatch "^/.*/\.git/">
    Require all denied
</DirectoryMatch>

# ===================================================================
# 📁 FILE UPLOAD RESTRICTIONS
# ===================================================================

# Block execution of uploaded files in uploads directory (if created)
<Directory "uploads">
    <Files "*">
        SetHandler default-handler
        RemoveHandler .php .phtml .php3 .php4 .php5 .php6 .phps .cgi .pl .py .js .jsp .sh .bat
        RemoveType .php .phtml .php3 .php4 .php5 .php6 .phps .cgi .pl .py .js .jsp .sh .bat
        php_flag engine off
    </Files>
</Directory>

# ===================================================================
# 🔒 FORCE HTTPS (Uncomment when SSL is enabled)
# ===================================================================

# RewriteCond %{HTTPS} off
# RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ===================================================================
# 🛡️ ADDITIONAL SECURITY MEASURES
# ===================================================================

# Limit request size (10MB)
LimitRequestBody 10485760

# Timeout settings
Timeout 60
KeepAliveTimeout 15

# Prevent hotlinking (uncomment if needed)
# RewriteCond %{HTTP_REFERER} !^$
# RewriteCond %{HTTP_REFERER} !^https://(www\.)?ukdataservices\.co\.uk/ [NC]
# RewriteRule \.(jpg|jpeg|png|gif|svg|css|js)$ - [F,L]

# ===================================================================
# 📧 EMAIL SECURITY
# ===================================================================

# Prevent email injection
<IfModule mod_rewrite.c>
    RewriteCond %{QUERY_STRING} (\[|\]|\(|\)|<|>|%0A|%0D|%22|%27|%3C|%3E|%00) [NC,OR]
    RewriteCond %{QUERY_STRING} (javascript:|vbscript:|onload|onerror|onclick) [NC]
    RewriteRule ^(.*)$ - [F,L]
</IfModule>

# ===================================================================
# 🔍 BLOCK COMMON ATTACK PATTERNS
# ===================================================================

# Block SQL injection attempts
<IfModule mod_rewrite.c>
    RewriteCond %{QUERY_STRING} (union|select|insert|delete|update|drop|create|alter|exec|execute) [NC]
    RewriteRule ^(.*)$ - [F,L]
    
    # Block XSS attempts
    RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
    RewriteCond %{QUERY_STRING} (<|%3C)([^e]*e)+mbed.*(>|%3E) [NC,OR]
    RewriteCond %{QUERY_STRING} (<|%3C)([^o]*o)+bject.*(>|%3E) [NC,OR]
    RewriteCond %{QUERY_STRING} (<|%3C)([^i]*i)+frame.*(>|%3E) [NC]
    RewriteRule ^(.*)$ - [F,L]
</IfModule>

# ===================================================================
# 🤖 BLOCK BAD BOTS AND SCRAPERS
# ===================================================================

# Block known bad bots (add more as needed)
<IfModule mod_rewrite.c>
    RewriteCond %{HTTP_USER_AGENT} (bot|crawler|spider|scraper|harvest|extract|grab|scan|copy|wget|curl) [NC]
    RewriteCond %{HTTP_USER_AGENT} !(googlebot|bingbot|facebookexternalhit|linkedinbot|twitterbot|whatsapp|telegrambot) [NC]
    RewriteCond %{HTTP_USER_AGENT} !^$ [NC]
    RewriteRule ^(.*)$ - [F,L]
</IfModule>

# ===================================================================
# 📊 PERFORMANCE & CACHING
# ===================================================================

# Enable compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

# Set cache headers for static files
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType application/x-javascript "access plus 1 month"
    ExpiresByType image/x-icon "access plus 1 year"
</IfModule>

# ===================================================================
# END OF ENHANCED SECURITY CONFIGURATION
# ===================================================================
