Options -Indexes +SymLinksIfOwnerMatch
RewriteEngine On
RewriteBase /

# Preserve /.well-known for SSL/Certbot
RewriteRule ^\.well-known/ - [L]

# Block direct access to internal app directory
RewriteRule ^app/ - [F,L]

# ----------------------------------------------------------------------
# Canonical Redirection (301 Permanent Redirect)
# 1) Strip www. prefix dynamically for any domain
# 2) Force HTTPS across all requests (bypasses localhost for local dev)
# ----------------------------------------------------------------------
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteCond %{HTTP_HOST} !^localhost [NC]
RewriteCond %{HTTP_HOST} !^127\.0\.0\.1 [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# Force UTF-8 Charset for Text & Markdown files (fixes Thai font in Firefox/Opera)
AddDefaultCharset UTF-8
AddCharset UTF-8 .md .txt .json .xml

# Dynamic XML Sitemap, Robots.txt, PWA Manifest & LLM text endpoints
RewriteRule ^robots\.txt$ robots.php [L,QSA]
RewriteRule ^sitemap\.xml$ sitemap.php [L,QSA]
RewriteRule ^manifest\.json$ manifest.php [L,QSA]
RewriteRule ^llms\.txt$ llms_auto.php [L,QSA]
RewriteRule ^llms[_-]full\.txt$ llms_auto.php?full=yes [L,QSA]

# Serve existing files and directories directly
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Front controller routing
RewriteRule ^(.*)$ index.php [L,QSA]

<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"

    # ------------------------------------------------------------------
    # Efficient Browser Caching Policy (Google PageSpeed / Web Vitals)
    # ------------------------------------------------------------------

    # 1 Year Cache for Static Images & Media (WebP, AVIF, PNG, JPG, SVG, ICO)
    <FilesMatch "\.(ico|jpe?g|png|gif|webp|avif|svg|mp4|webm|ogg)$">
        Header set Cache-Control "max-age=31536000, public, immutable"
    </FilesMatch>

    # 1 Year Cache for Web Fonts (WOFF2, WOFF, TTF, OTF, EOT)
    <FilesMatch "\.(woff2?|ttf|otf|eot)$">
        Header set Cache-Control "max-age=31536000, public, immutable"
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>

    # 30 Days Cache for Stylesheets & JavaScript (versioned with ?v=x.x)
    <FilesMatch "\.(css|js)$">
        Header set Cache-Control "max-age=2592000, public"
    </FilesMatch>

    # 7 Days Cache for Web App Manifest
    <FilesMatch "\.(webmanifest|manifest\.json)$">
        Header set Cache-Control "max-age=604800, public"
    </FilesMatch>
</IfModule>
