Leigh Harrison
Leigh Harrison

Reputation: 23

Exclude a deep subdirectory from an .htaccess RedirectMatch

The site's .htaccess file has this existing command:

RedirectMatch 404 /directory(/|$)

An exception is required to make files from one deep subdirectory accessible while still returning a 404 for all other files under directory. The path to the accessible directory is:

/directory/sub/sub/sub/sub

If I comment out the existing RedirectMatch, the files in the subdirectory are accessible, but so are all the other contents of /directory. I've tried retaining the RedirectMatch and putting a RewriteRule at the top of the .htaccess file:

RewriteRule ^/directory/sub/sub/sub/sub/ - [L]

I've tried replacing the the RedirectMatch with a RewriteCond and RewriteRule:

RewriteCond %{REQUEST_URI} ^/directory/ 
RewriteCond %{REQUEST_URI} !^/directory/sub/sub/sub/sub/.*$
RewriteRule ^/directory/(.*)$ - [L,R=404]

So far nothing has been effective. Any pointers?

Upvotes: 2

Views: 482

Answers (1)

Mike Rockétt
Mike Rockétt

Reputation: 9007

You can use a negative lookahead to exclude the subdirectory, like so:

 RedirectMatch 404 /directory(?!/sub/sub/sub/sub)

You'll also notice that I've removed the check for the trailing slash or end of string. Reason being: directories always have trailing slash (unless DirectorySlash is set to off). Also, no need to check for the end of the path because you're matching everything in directory and the subdirectory (for exclusion).

Upvotes: 1

Related Questions