atxpunkrock
atxpunkrock

Reputation: 514

Apache htaccess redirect directory and some contents

I'm currently trying to get Apache to redirect any requests for a directory or it's contents to a single file. The directory in question is /press. This happens to contain multiple images that are being used by other pages on the site. I want to redirect /press and /press/* to /press-materials/ but allow any image requests (e.g. /press/logo.png) to be completed. I've tried a few solutions and get one aspect of the redirect working but it doesn't meet the other criteria.

I'm a novice when it comes to Apache and REGEX (Something I knowingly need to work on) so this may be a simple fix.

Here is the htaccess call that redirects /press to /press-materials but /press/filename returns a 404 error.

RewriteRule ^press/$ /press-materials/ [R,L]

After 6 hours that's as far as I've gotten. Any help would be most appreciated.

Upvotes: 0

Views: 255

Answers (1)

speakr
speakr

Reputation: 4209

Assuming that you want to allow all requests to files which actually exist in /press (like /press/logo.png):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^press/.* /press-materials/ [R,L]

This performs the rewrite only if no existing file in /press has been requested.

Another solution to allow only specific file types (e.g. only *.jpg, *.png, *.gif) and only if they are existing in the /press directory but not in a subdirectory:

RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_URI} !^/press/[^\/]+\.(png|jpg|gif)$
RewriteRule ^press/.* /press-materials/ [R,L]

More information about rewrite conditions can be found here.

Upvotes: 2

Related Questions