htaccess - redirect directory to file with same name

I seem to be having an issue I have found no solution to.

I have a directory and a file with the same name set up and I cannot seem to find a way to redirect the directory to the file in the root folder. All the info I found was for rewriting or redirect to a file in the subdirectory.

dir: example.com/en-gb/

file: example.com/en-gb (extension removed with htaccess)

Current htaccess (relevant part):

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]
RewriteRule ^$ /en-gb [L]
RewriteCond %{REQUEST_URI} ^/en-gb/$
RewriteRule . ../en-gb [R,L]

This just results in the following error:

You don't have permission to access /en-gb/.html on this server.

Any ideas? Is this even possible?

1 answer

  • answered 2017-06-17 18:39 MrWhite

    Ordinarily, when you request /directory, mod_dir issues a 301 redirect to append a trailing slash, ie. /directory/ (to "fix" the URL). mod_dir is then able to serve the directory index document from within that directory.

    Unfortunately, this would appear to occur before mod_rewrite is able to process the request. So, you are going to have to disable this behaviour in .htaccess:

    DirectorySlash Off
    

    You can then internally rewrite the request to the file instead. eg. /directory gets internally rewritten to /directory.html if it exists:

    RewriteCond %{DOCUMENT_ROOT}/$1.html -f
    RewriteRule ^([^.]+)$ $1.html [L]
    

    However, disabling DirectorySlash has it's caveats - you are going to have to make sure that any requests for directories already have trailing slashes (or check for this in .htaccess as well). And note the security warning in the docs.

    Reference:
    https://httpd.apache.org/docs/current/mod/mod_dir.html#directoryslash