RewriteEngine On

# 1. Force HTTPS + remove www (single 301 redirect)
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://thetaevno.com%{REQUEST_URI} [R=301,L]

# 2. Remove trailing slashes — single or multiple (except root)
RewriteCond %{REQUEST_URI} ^(.+?)/+$
RewriteRule ^ https://thetaevno.com%1 [R=301,L]

# 3. Redirect /index.html to / so the canonical homepage URL stays clean
RewriteCond %{THE_REQUEST} ^[A-Z]+\s/+index\.html[\s?] [NC]
RewriteRule ^index\.html$ / [R=301,L]

# 4. Clean URLs, redirect half: a DIRECT .html request 301s to the
#    extensionless URL (parity with Cloudflare Pages, consolidates any
#    already-indexed .html URLs). THE_REQUEST-gated so the internal rewrite
#    in rule 5 can't loop; index.html is rule 3's business.
RewriteCond %{THE_REQUEST} ^[A-Z]+\s/+[^?\s]+\.html[\s?] [NC]
RewriteCond %{REQUEST_URI} !^/index\.html$ [NC]
RewriteRule ^(.+)\.html$ /$1 [R=301,L]

# 5. Clean URLs, serve half: an extensionless request is served from the
#    matching .html file (internal rewrite, no redirect). No !-d guard on
#    purpose: /articles must serve articles.html even though the articles/
#    directory exists.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L]

# 6. Real 404 page (ErrorDocument preserves the 404 status)
ErrorDocument 404 /404.html

# Security headers
<IfModule mod_headers.c>
  Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" env=HTTPS
  Header always set X-Content-Type-Options "nosniff"
  Header always set X-Frame-Options "SAMEORIGIN"
  Header always set Referrer-Policy "strict-origin-when-cross-origin"
  Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: https://www.youtube.com; frame-src https://www.youtube.com; connect-src 'self'"
</IfModule>
