Forum Moderators: phranque

Message Too Old, No Replies

How to return 403 or 404 for existing folder?

How to return 403 or 404 for existing folder?

         

cyberbob

12:49 pm on Aug 26, 2008 (gmt 0)

10+ Year Member



Hi all,

I have this code, which I put into site root, and I want to hide all folders inside site root, so I am returning 403 for them. The questions are:
1) I need this code to be applied only for internal directories and files inside them, but not for site root directory.
2) How to return 404 error code instead of 403?


RewriteEngine on

# if it exists as a directory
RewriteCond %{REQUEST_FILENAME} -d [OR]
# then send forbidden (403)
RewriteRule (.*) - [F]

jdMorgan

6:07 pm on Aug 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Something like:

# if requested subdirectory exists
RewriteCond %{DOCUMENT_ROOT}/$1 -d
# if URL-path indicates a subdirectory (plus any additional filenames, etc.)
RewriteRule ^(([^/]+/)+) /some-filepath-that-does-not-exist-so-as-to-force-a-404 [L]

Here, the directory-path part of the requested URL is extracted into variable $1 (the requested URL may contain a filename in addition to this directory-path, but it is not relevant). Then, we append that directory path to %{DOCUMENT_ROOT}, essentially converting the requested directory path from a URL to a fully-localized server directory path. Then we check that to see if it exists (although this check is not really needed, I left it in just in case you planned to elaborate this code later If it is not needed, then all that you need to do is to exclude any custom 404 error document's directory from this rewrite). If the directory-path resolves to an existing directory, then we rewrite the request to some filepath that does not exist, so as to force a 404-Not Found.

Jim

[edited by: jdMorgan at 6:08 pm (utc) on Aug. 26, 2008]

cyberbob

7:42 am on Aug 28, 2008 (gmt 0)

10+ Year Member



Thanks, jdMorgan! It works, but another problem is that now I get "internal server error 500" in subdirectories (which are subdomains from root in fact).

I have .htaccess in root site dir with these lines:


RewriteEngine on
RewriteRule ^(([^/]+/)+) /page-not-found-404 [L]

How can I limit this rules to not apply when I ask for subdomains (without putting .htaccess with rewriteengine off" in each subdirectory), but only make it works for directories?

Thanks in advance!

jdMorgan

4:06 pm on Aug 28, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You may need to exclude those subdirectories explicitly, since mod_rewrite has no idea which subdirectories are for subdomains and which are just subdirectories of the main domain.

This is typically done by adding RewriteConds based on %{REQUEST_URI} to the rule.

Jim

cyberbob

4:46 pm on Aug 28, 2008 (gmt 0)

10+ Year Member



Thanks, Jim!

It works now. Indeed, rather simple and easy :)