################################################################################
# Apache .htaccess Configuration for Workflow Automation
# cPanel + Passenger WSGI
#
# This file configures Apache to properly serve the Flask application
# through Passenger WSGI on cPanel hosting.
#
# IMPORTANT: Update paths with your actual username!
# Replace /home/username/ with your actual home directory path
################################################################################

# ══════════════════════════════════════════════════════════════════
# Passenger WSGI Configuration
# ══════════════════════════════════════════════════════════════════

# Enable Passenger
PassengerEnabled On

# Set application root directory
# IMPORTANT: Update this path with your actual username
PassengerAppRoot /home/username/workflow-automation

# Set Python interpreter from virtual environment
# IMPORTANT: Update this path with your actual username
PassengerPython /home/username/workflow-automation/venv/bin/python3

# Set startup file
PassengerStartupFile passenger_wsgi.py

# Application environment (production/development)
PassengerAppEnv production

# Passenger performance settings
PassengerMinInstances 1
PassengerMaxPoolSize 6
PassengerPoolIdleTime 300
PassengerMaxRequests 1000

# Restart application when this file is touched
PassengerRestartDir /home/username/workflow-automation/tmp

# ══════════════════════════════════════════════════════════════════
# URL Rewriting
# ══════════════════════════════════════════════════════════════════

# Enable rewrite engine
RewriteEngine On
RewriteBase /

# Force HTTPS (SSL) - Redirect all HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Force www (optional - uncomment if you want to force www)
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Remove www (optional - uncomment if you want to remove www)
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [L,R=301]

# Remove trailing slash (optional)
# RewriteCond %{REQUEST_FILENAME} !-d
# RewriteCond %{REQUEST_URI} (.+)/$
# RewriteRule ^ %1 [L,R=301]

# ══════════════════════════════════════════════════════════════════
# Security Headers
# ══════════════════════════════════════════════════════════════════

<IfModule mod_headers.c>
    # Prevent MIME type sniffing
    Header set X-Content-Type-Options "nosniff"
    
    # Prevent clickjacking
    Header set X-Frame-Options "SAMEORIGIN"
    
    # Enable XSS protection
    Header set X-XSS-Protection "1; mode=block"
    
    # Referrer policy
    Header set Referrer-Policy "strict-origin-when-cross-origin"
    
    # Content Security Policy (adjust as needed)
    Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; img-src 'self' data: https:; font-src 'self' data: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; connect-src 'self'; frame-ancestors 'self';"
    
    # Permissions Policy (formerly Feature Policy)
    Header set Permissions-Policy "geolocation=(), microphone=(), camera=()"
    
    # Remove server signature
    Header unset Server
    Header unset X-Powered-By
    
    # HSTS (HTTP Strict Transport Security) - Force HTTPS for 1 year
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
</IfModule>

# ══════════════════════════════════════════════════════════════════
# Cache Control
# ══════════════════════════════════════════════════════════════════

<IfModule mod_expires.c>
    ExpiresActive On
    
    # Default expiration
    ExpiresDefault "access plus 1 month"
    
    # HTML (no cache for dynamic content)
    ExpiresByType text/html "access plus 0 seconds"
    
    # CSS
    ExpiresByType text/css "access plus 1 year"
    
    # JavaScript
    ExpiresByType text/javascript "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 year"
    ExpiresByType application/x-javascript "access plus 1 year"
    
    # Images
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType image/x-icon "access plus 1 year"
    
    # Fonts
    ExpiresByType font/ttf "access plus 1 year"
    ExpiresByType font/otf "access plus 1 year"
    ExpiresByType font/woff "access plus 1 year"
    ExpiresByType font/woff2 "access plus 1 year"
    ExpiresByType application/font-woff "access plus 1 year"
    
    # JSON
    ExpiresByType application/json "access plus 0 seconds"
    
    # XML
    ExpiresByType application/xml "access plus 0 seconds"
    ExpiresByType text/xml "access plus 0 seconds"
</IfModule>

# Cache-Control headers
<IfModule mod_headers.c>
    # Static assets - cache for 1 year
    <FilesMatch "\.(jpg|jpeg|png|gif|webp|svg|ico|css|js|woff|woff2|ttf|otf)$">
        Header set Cache-Control "max-age=31536000, public, immutable"
    </FilesMatch>
    
    # HTML - no cache
    <FilesMatch "\.(html|htm)$">
        Header set Cache-Control "no-cache, no-store, must-revalidate"
        Header set Pragma "no-cache"
        Header set Expires "0"
    </FilesMatch>
</IfModule>

# ══════════════════════════════════════════════════════════════════
# Compression (Gzip)
# ══════════════════════════════════════════════════════════════════

<IfModule mod_deflate.c>
    # Compress HTML, CSS, JavaScript, Text, XML and fonts
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
    AddOutputFilterByType DEFLATE application/x-font
    AddOutputFilterByType DEFLATE application/x-font-opentype
    AddOutputFilterByType DEFLATE application/x-font-otf
    AddOutputFilterByType DEFLATE application/x-font-truetype
    AddOutputFilterByType DEFLATE application/x-font-ttf
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE font/opentype
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/ttf
    AddOutputFilterByType DEFLATE image/svg+xml
    AddOutputFilterByType DEFLATE image/x-icon
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/javascript
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/xml
    
    # Remove browser bugs (only needed for really old browsers)
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
    Header append Vary User-Agent
</IfModule>

# ══════════════════════════════════════════════════════════════════
# File Protection
# ══════════════════════════════════════════════════════════════════

# Disable directory browsing
Options -Indexes

# Disable server signature
ServerSignature Off

# Protect sensitive files
<FilesMatch "^(config\.yaml|\.env|requirements\.txt|\.git.*|\.htpasswd|\.htaccess)$">
    Order allow,deny
    Deny from all
</FilesMatch>

# Protect Python files from direct access
<FilesMatch "\.py$">
    Order allow,deny
    Deny from all
</FilesMatch>

# Protect database files
<FilesMatch "\.db$">
    Order allow,deny
    Deny from all
</FilesMatch>

# Protect log files
<FilesMatch "\.log$">
    Order allow,deny
    Deny from all
</FilesMatch>

# Protect backup files
<FilesMatch "\.(bak|backup|old|orig|save|swp|tmp)$">
    Order allow,deny
    Deny from all
</FilesMatch>

# ══════════════════════════════════════════════════════════════════
# Error Pages (Optional)
# ══════════════════════════════════════════════════════════════════

# Custom error pages (uncomment and create these files if needed)
# ErrorDocument 400 /error/400.html
# ErrorDocument 401 /error/401.html
# ErrorDocument 403 /error/403.html
# ErrorDocument 404 /error/404.html
# ErrorDocument 500 /error/500.html
# ErrorDocument 503 /error/503.html

# ══════════════════════════════════════════════════════════════════
# PHP Configuration (if needed for other parts of the site)
# ══════════════════════════════════════════════════════════════════

<IfModule mod_php7.c>
    # Disable PHP execution in uploads directory
    php_flag engine off
</IfModule>

# ══════════════════════════════════════════════════════════════════
# MIME Types
# ══════════════════════════════════════════════════════════════════

<IfModule mod_mime.c>
    # JavaScript
    AddType application/javascript js
    AddType application/x-javascript js
    
    # JSON
    AddType application/json json
    
    # Web fonts
    AddType font/ttf ttf
    AddType font/otf otf
    AddType font/woff woff
    AddType font/woff2 woff2
    AddType application/font-woff woff
    AddType application/font-woff2 woff2
    
    # Images
    AddType image/webp webp
    AddType image/svg+xml svg svgz
    
    # Video
    AddType video/mp4 mp4
    AddType video/webm webm
    
    # Audio
    AddType audio/mp3 mp3
    AddType audio/ogg ogg
    
    # Other
    AddType application/pdf pdf
    AddType text/plain txt
</IfModule>

# ══════════════════════════════════════════════════════════════════
# Character Encoding
# ══════════════════════════════════════════════════════════════════

# Set default charset to UTF-8
AddDefaultCharset UTF-8
<IfModule mod_mime.c>
    AddCharset UTF-8 .html .css .js .xml .json .rss .atom
</IfModule>

# ══════════════════════════════════════════════════════════════════
# Performance Optimization
# ══════════════════════════════════════════════════════════════════

# Enable Keep-Alive
<IfModule mod_headers.c>
    Header set Connection keep-alive
</IfModule>

# Limit request body size (adjust as needed)
# LimitRequestBody 10485760

# ══════════════════════════════════════════════════════════════════
# IP Blocking (Optional)
# ══════════════════════════════════════════════════════════════════

# Block specific IPs (uncomment and add IPs as needed)
# <Limit GET POST>
#     Order allow,deny
#     Deny from 123.456.789.0
#     Deny from 987.654.321.0
#     Allow from all
# </Limit>

# Allow only specific IPs (uncomment and add IPs as needed)
# <Limit GET POST>
#     Order deny,allow
#     Deny from all
#     Allow from 123.456.789.0
#     Allow from 987.654.321.0
# </Limit>

# ══════════════════════════════════════════════════════════════════
# Rate Limiting (Optional - requires mod_ratelimit)
# ══════════════════════════════════════════════════════════════════

# <IfModule mod_ratelimit.c>
#     <Location />
#         SetOutputFilter RATE_LIMIT
#         SetEnv rate-limit 400
#     </Location>
# </IfModule>

# ══════════════════════════════════════════════════════════════════
# Additional Security
# ══════════════════════════════════════════════════════════════════

# Disable ETags (optional - for better caching control)
# FileETag None

# Prevent access to hidden files
<FilesMatch "^\.">
    Order allow,deny
    Deny from all
</FilesMatch>

# ══════════════════════════════════════════════════════════════════
# Notes
# ══════════════════════════════════════════════════════════════════

# IMPORTANT REMINDERS:
# 1. Update all /home/username/ paths with your actual username
# 2. Test after any changes: touch tmp/restart.txt
# 3. Check error logs if issues occur: ~/logs/error_log
# 4. Backup this file before making changes
# 5. Some directives may not work on all hosting providers
# 6. Contact your hosting provider if you need specific modules enabled

# To restart the application after changes:
# touch /home/username/workflow-automation/tmp/restart.txt

# To check if .htaccess is working:
# 1. Check if HTTPS redirect works
# 2. Try accessing a .py file directly (should be blocked)
# 3. Check response headers in browser dev tools
# 4. Test compression with online tools

################################################################################
# END OF .htaccess CONFIGURATION
################################################################################
