.htaccess RewriteCond where URI does not contain domain

.htaccess, apache, mod-rewrite, php, regex

Solution

This is terrific question and if I could I would have upvoted 10+ times. I am posting my answer even though you have an accepted answer here as I really had to dig through all my Apache resources to come up with the answer. Here is the rule you will need for this problem:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST}:%{REQUEST_URI} !^([^:]+):/resources/[^/]+/\1/.+ [NC]
RewriteRule ^resources/[^/]+/[^/]+/.+ - [F,NC,NE]

PS: Since we cannot use `%` variables on RHS as back-reference, I am using special regex back-reference variable `\1` in the `RewriteCond` here.

Problem

I have looked around on Google and StackOverflow for the answer to this question, but the fact that I don't know much about .htaccess doesn't help me decide what the correct answers for my situation are, so I am asking here. My situation is that I have several sites that are using the same physical directory as their root on the server. This is all working fine but I wanted to make sure that each site can't access each others images etc from the browser unless they are on the correct domain. Currently I have a file structure like this: ``` /resources/{resource}/{full_domain_name} ``` So for example `www.domain.co.uk` would have a structure like this: ``` http://www.domain.co.uk/resources/images/www.domain.co.uk/some_image.jpg ``` But if `www.domain_2.co.uk` exists using the same physical directory for the site root then they can look at other domain's resources from their own domain, like this: ``` http://www.domain_2.co.uk/resources/images/www.domain.co.uk/some_image.jpg ``` This isn't really a major problem since there is absolutely no sensitive information stored in these directories, but it's more of an annoyance and I would rather users were not able to do it (not that anyone actually has so far). I tried putting a .htaccess file into the /resources directory but I'm stuck with the regular expressions etc. I basically want to make sure that the URI contains the current domain name otherwise redirect to a 403 error page. This is what I came up with: ``` RewriteCond %{REQUEST_URI} !^(/resources/[^/]*/%{HTTP_HOST})(.*)$ RewriteRule ^(.*)$ /error/403.php ``` The reason I put in the `[^/]` bit is because there are several folders, for example: ``` /resources/images/{full_domain_name} /resources/scripts/{full_domain_name} /resources/stylesheets/{full_domain_name} ``` Could anybody help me with these conditions? Any help would be appreciated.

Original source