# Books by Leggs — Apache config
# Works at the domain root OR inside a subfolder (e.g. /michaellom/) with no edits.

# Default page
DirectoryIndex index.php

# Protect the data directory (reviews store) from direct web access
<FilesMatch "\.(json)$">
    Require all denied
</FilesMatch>

# Clean URLs: no .php extension, canonical form ends with a trailing slash.
#   /about.php  ->  /about/   (301)
#   /about      ->  /about/   (301)
#   /about/     ->  serves about.php internally
#   unknown URL ->  serves 404.php (styled page, 404 status)
<IfModule mod_rewrite.c>
    RewriteEngine On

    # index(.php) -> the directory root (e.g. .../index.php -> .../)
    # THE_REQUEST keeps the full request path, so the subfolder is preserved.
    RewriteCond %{REQUEST_METHOD} =GET
    RewriteCond %{THE_REQUEST} \s/+(.*?)index(?:\.php)?/?[\s?] [NC]
    RewriteRule ^ /%1 [R=301,L]

    # Externally requested .php -> clean URL with trailing slash (GET only,
    # so form POSTs to a .php action are never redirected and never lose data)
    RewriteCond %{REQUEST_METHOD} =GET
    RewriteCond %{THE_REQUEST} \s/+([^.\s?]+)\.php[\s?/] [NC]
    RewriteRule ^ /%1/ [R=301,L]

    # Add a trailing slash to an extensionless URL that maps to a .php file.
    # Uses REQUEST_FILENAME (absolute filesystem path) so it is subfolder-safe.
    RewriteCond %{REQUEST_METHOD} =GET
    RewriteCond %{REQUEST_URI} !(/$|\.)
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^ %{REQUEST_URI}/ [R=301,L]

    # Internally serve /path/ from path.php (only if that .php actually exists).
    # %1 captures the filesystem path without the trailing slash -> subfolder-safe.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} ^(.*?)/?$
    RewriteCond %1.php -f
    RewriteRule ^(.+?)/?$ $1.php [L]

    # Anything else that isn't a real file/dir -> styled 404 page (sets 404 status itself).
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ 404.php [L]
</IfModule>

# Fallback 404 if mod_rewrite is unavailable (root installs only).
<IfModule !mod_rewrite.c>
    ErrorDocument 404 /404.php
</IfModule>

# Basic 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>
