RewriteEngine On

# Serve real files/directories directly (css/js/icons/manifest/sitemaps/etc.) without rewriting
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Block direct access to app internals — only entry-point PHP files at the root should run
RewriteRule ^(includes|cron|database)(/|$) - [F,L]
<FilesMatch "\.(sql|md)$">
  Require all denied
</FilesMatch>
<Files "config.php">
  # config.php must stay reachable by PHP includes, but never served directly over HTTP
</Files>
RewriteRule ^config\.php$ - [F,L]
RewriteRule ^config\.example\.php$ - [F,L]

# Enforce a trailing slash on clean URLs (skip requests for files with an extension)
RewriteCond %{REQUEST_URI} !\.[a-zA-Z0-9]+$
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.+)$ /$1/ [L,R=301]

# Specific static-style routes first (must come before the generic provider catch-all)
RewriteRule ^category/([a-z0-9-]+)/?$ category.php?slug=$1 [L,QSA]
RewriteRule ^guides/?$ guides.php [L,QSA]
RewriteRule ^guides/([a-z0-9-]+)/?$ guide.php?slug=$1 [L,QSA]
RewriteRule ^glossary/?$ glossary.php [L,QSA]
RewriteRule ^glossary/([a-z0-9-]+)/?$ glossary-term.php?slug=$1 [L,QSA]
RewriteRule ^compare/?$ compare.php [L,QSA]
RewriteRule ^search/?$ search.php [L,QSA]
RewriteRule ^offline/?$ offline.php [L,QSA]

# Provider + article catch-all (must come last — matches any remaining one/two-segment path)
RewriteRule ^([a-z0-9-]+)/([a-z0-9-]+)/?$ article.php?provider=$1&slug=$2 [L,QSA]
RewriteRule ^([a-z0-9-]+)/?$ provider.php?slug=$1 [L,QSA]

# Compression
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html text/css text/xml application/javascript application/json image/svg+xml application/xml
</IfModule>

# Caching
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/svg+xml "access plus 1 year"
  ExpiresByType image/webp "access plus 1 year"
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"
  ExpiresByType application/manifest+json "access plus 1 week"
</IfModule>

# Security headers
<IfModule mod_headers.c>
  Header set X-Content-Type-Options "nosniff"
  Header set X-Frame-Options "SAMEORIGIN"
  Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

# Correct MIME type for the web app manifest on hosts that don't already map it
<IfModule mod_mime.c>
  AddType application/manifest+json .webmanifest
  AddType application/manifest+json .json
</IfModule>

ErrorDocument 404 /404.php
