RewriteEngine On
RewriteBase /

# Force HTTPS and WWW
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} !^www\.centralfarmersmarket\.com$ [NC]
RewriteRule ^ https://www.centralfarmersmarket.com%{REQUEST_URI} [R=301,L]

# Redirect index files to directory URLs
RewriteCond %{THE_REQUEST} \s/+(.*/)?index\.(html?|php)[\s?] [NC]
RewriteRule ^(.*/)?index\.(html?|php)$ https://www.centralfarmersmarket.com/$1 [R=301,L]

# Redirect direct .html requests to clean trailing-slash URLs
RewriteCond %{THE_REQUEST} \s/+(.+?)\.html[\s?] [NC]
RewriteRule ^(.+?)\.html$ /$1/ [R=301,L]

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

# Add trailing slash to extensionless URLs
RewriteCond %{REQUEST_URI} !\.[a-zA-Z0-9]{1,8}$
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.+)$ /$1/ [R=301,L]

# Internally serve matching .html files
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^(.+)/$ $1.html [L]
