kyle.stearns
kyle.stearns

Reputation: 2346

htaccess - check if files exist in current directory and subdirectory, if not redirect to 404 page

I'm trying to perform an operation in my .htaccess file that checks if multiple files exist - and if they don't redirect to a 404 page.

Request URL: //mydomain.com/page-name

First, it will check if this file exists. If the file does not exist it will check if the file exists in a subdirectory; it will check if the following file exists: //mydomain.com/h/page-name.

Lastly, if that file does not exist it will redirect the user to a 404 at: //mydomain.com/404.php.

Is it possible to walk through multiple conditions to perform a redirect as I've described here? Is there a better method/solution?

Upvotes: 0

Views: 2208

Answers (1)

kyle.stearns
kyle.stearns

Reputation: 2346

After a bit of messing around I figured it out. Hope it helps someone else! You can place the following code in your .htaccess to get achieve this.

RewriteEngine On

# if file exists in root directory
# redirect to file in root directory
RewriteCond  %{DOCUMENT_ROOT}/$1 -f
RewriteRule  ^(.*)$  $1  [L,QSA]

# if file exists in /h/ directory
# redirect to file in /h/ directory
RewriteCond  %{DOCUMENT_ROOT}/h/$1 -f
RewriteRule ^(.*)$ h/$1 [L,QSA]

# if we've gotten this far let's just
# send 'em to the 404
RewriteRule ^(.*)$ 404.php [L,QSA]

Upvotes: 3

Related Questions