RewriteEngine On

# Fix for nginx proxy to avoid internal server errors
RewriteBase /

# Redirect all traffic to the public folder, but allow existing files/directories
RewriteCond %{REQUEST_URI} !^/public/
RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} -d
RewriteRule ^(.*)$ /public/$1 [L,QSA]

# Handle cases where the file doesn't exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /public/index.php [L]

# Ensure directory listing is disabled
Options -Indexes

# Enable compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
</IfModule>

# Leverage browser caching
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/html "access plus 1 month"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType application/x-shockwave-flash "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
</IfModule>

# Basic security headers
<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "SAMEORIGIN"
    Header set X-XSS-Protection "1; mode=block"
</IfModule>

# Handle 404 errors
ErrorDocument 404 /public/404.html

# Handle PHP execution if needed
<FilesMatch "\.php$">
    SetHandler application/x-httpd-php
</FilesMatch>

# Deny access to sensitive files
<FilesMatch "^\.(htaccess|htpasswd|env|ini|log|sh|sql|bak|config)$">
    Require all denied
</FilesMatch>
