1

I have the following rewrite rule which converts example.com/anything/ to load the page at example.com/anything.html

RewriteRule ^([A-Za-z0-9-]+)/?$ $1.html [L]

I need an exception to this rule when a physical directory or file exists. For example, if there is a physical directory at example.com/test/ then it should load an index from the /test/ directory, instead of rewriting it to example.com/test.html

I believe I need rewrite conditions RewriteCond with !-d and !-f similar to:

https://httpd.apache.org/docs/2.4/rewrite/remapping.html#fallback-resource

I'm having trouble figuring out how to write these conditions.

Solution:

Prefixing the condition:

RewriteCond %{REQUEST_FILENAME} !-d

Allows directories to be read as they usually would. Also my regex pattern match doesn't consider file names with extensions (lacking a dot .), so files such as example.css will be read as usual also.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z0-9-]+)/?$ $1.html [L]
MrWhite
  • 11,643
  • 4
  • 25
  • 40

1 Answers1

0

Yes, as you suggest, you need an additional condition to test that it is not a directory. For example, in .htaccess:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z0-9-]+)/?$ $1.html [L]

The negated CondPattern !-d checks that the REQUEST_FILENAME does not map to a directory. The REQUEST_FILENAME variable (in a directory or .htaccess context) holds the absolute filesystem path of the file/directory that the request maps to.

I don't think you need to check for files, since a file shouldn't match the RewriteRule pattern ^([A-Za-z0-9-]+)/?$ - unless you have files without file extensions?


In the Apache docs you link to:

RewriteCond "/var/www/my_blog/%{REQUEST_FILENAME}" !-d

The format of this directive doesn't actually look correct to me, considering the example shows it being used in a directory context. (This format might be required in a server or virtualhost context, when the REQUEST_FILENAME is the same as REQUEST_URI - the URL-path of the request. However, this variable would then starts with a slash, so the above is still incorrect?!)

MrWhite
  • 11,643
  • 4
  • 25
  • 40