0

The site is html, I have 3 .html files that have 3 directories with the same name. BTW its apache2 on ubuntu 18

So...... file1.html /file1 file2.html /file2 an so on.

No problem if you don't turn off file extensions in your .htaccess file. But when doing that the directory is served up and you get a error. So here is my .htaccess config trying to use DirectorySlash Off. There is some other stuff going on in this file but I thought I'd leave it all in in case there are related cause/effect things going on here.

# BEGIN
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
Options +MultiViews
DirectorySlash Off
# Rewrite to file when file and directory both exist with the same name
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^([^.]+)$ $1.html [L]
# Allows files to be loaded without extensions
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [NC,L]
# Removes the file extensions
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]
Redirects from products to product directory
RewriteRule ^products/(.*)$ /product/$1 [R=301,NC,L]
</IfModule>
# END
brooksly
  • 5
  • 3

1 Answers1

0

You could be able to give a priority to file when it request comes without / with same name with directory as well as removing file extension , html , like this :

DirectorySlash Off
RewriteEngine on 
RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index)?(.*?)\.(html)[\s?/] [NC]
RewriteRule ^ /%1%2 [R=302,L,NE]
RewriteCond %{REQUEST_FILENAME}   !-f 
RewriteCond %{REQUEST_FILENAME}\.html -f 
RewriteRule ^(.*) /$1.html [L]
RewriteCond %{REQUEST_FILENAME}   !-f 
RewriteCond %{REQUEST_URI} !\/$
RewriteRule ^(.*) %{REQUEST_URI}/ [L,R=302]

Then add your rest rules:

RewriteRule ^products/(.*)$ /product/$1 [R=301,NC,L]

So , by the code above , HTML extension will be removed then server will check first if there is an HTML file match this request then,if there is a directory match this request .

Clear browser cache then test it , if it is Ok , change 302 to 301 to get permanent redirection

For more info , you can also refer to my previous answer :

Remove .php and .html extensions AND have directories with same name?

Mohammed Elhag
  • 4,272
  • 1
  • 10
  • 18