How to make .htaccess rewrite rule for request filename work with directories with index files?

Viewed 39

This is the .htaccess I am using.

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} -f [OR]
 RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} -d
 RewriteRule (.*)$ https://sub.example.com/$1 [R=301,L]
</IfModule>

When a specific file path like path1/path2/index.html is requested, it works fine and and does't rewrite. But if a path like path1/path2/ is requested, it redirect even if there is a DirectoryIndex file like index.html in that directory. What is an easy way to fix this?

1 Answers

As I suggested in comment above, something like this should work:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?:www\.)?example\.com$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . https://sub.example.com%{REQUEST_URI} [R=301,L,NE]
Related