<IfModule mod_rewrite.c>
    Options -Indexes

    RewriteEngine On

    # Preserve API auth headers for Laravel/Sanctum.
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    RewriteCond %{HTTP:x-xsrf-token} .
    RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]

    # Keep old /public URLs working, but canonicalize them to the app root.
    RewriteCond %{THE_REQUEST} \s/+[^\s?]*/public/?[?\s] [NC]
    RewriteRule ^public/?$ ./ [R=301,L]

    RewriteCond %{THE_REQUEST} \s/+[^\s?]*/public/ [NC]
    RewriteRule ^public/(.*)$ $1 [R=301,L]

    # Bare app root (e.g. /admin/): with cached routes Laravel trims the trailing
    # slash, loses the subfolder base path and answers 405. Send it to the dashboard,
    # which itself redirects to the installer or login when needed.
    RewriteCond %{REQUEST_URI} ^(.*/)$
    RewriteRule ^$ %1dashboard [R=302,L]

    # Serve public assets without exposing the project root.
    RewriteRule ^(build|storage)/(.*)$ public/$1/$2 [L]
    RewriteRule ^(favicon\.ico|robots\.txt)$ public/$1 [L]

    # Block direct web access to Laravel internals and project files.
    RewriteRule ^(?:app|bootstrap|config|database|resources|routes|storage|tests|vendor)(?:/|$) - [F,L]
    RewriteRule ^(?:\.env(?:\..*)?|\.git(?:/|$)|\.editorconfig|\.gitattributes|\.gitignore|artisan|composer\.(?:json|lock)|package(?:-lock)?\.json|phpunit\.xml|vite\.config\.js|README\.md)$ - [F,L]

    # Let public/.htaccess finish internally rewritten requests.
    RewriteRule ^public/ - [L]

    # Serve existing public assets directly; send all routes to Laravel.
    RewriteCond public/$1 -f [OR]
    RewriteCond public/$1 -d
    RewriteRule ^(.*)$ public/$1 [L]

    RewriteRule ^(.*)$ index.php [L]
</IfModule>
