Kelvin Jones
Kelvin Jones

Reputation: 31

htaccess - Can I add a RewriteCond to another RewriteCond

OK, I'll strip this back because it's either easy or not possible...

.htaccess

RewriteCond %{REMOTE_ADDR} ^([^.]+)\.([^.]+)\.([^.]+)\.([^.]+)?
RewriteCond ^%1%2%3%4-%{REQUEST_FILENAME} -d
RewriteRule ^. - [L,NC]

This would protect folder viewing unless the users IP was specific to the requested foldername and the IP-URI named folder existed.

Need a solution using HTACCESS specifically.

Upvotes: 2

Views: 224

Answers (2)

MrWhite
MrWhite

Reputation: 45914

Yes, you can do something like this, but not quite in the way you are doing it. You just need to use the correct server variables.

RewriteCond ^%1%2%3%4-%{REQUEST_FILENAME} -d

The problem with this directive is that REQUEST_FILENAME is an absolute filesystem path. So, this effectively checks if ^2030113111-/home/user/public_html/foldername is a valid directory - which is going to fail. The TestString is also a string, not a regular expression, so the ^ prefix is also going to break things.

Instead, you could do something like:

RewriteCond %{REMOTE_ADDR} ^([^.]+)\.([^.]+)\.([^.]+)\.([^.]+)$
RewriteCond %{DOCUMENT_ROOT}/%1%2%3%4-$1 -d
RewriteRule (.+) - [L]

Where $1 is the URL-path matched by the RewriteRule pattern. The RewriteRule pattern is processed first, before, the RewriteCond directives that precede it.

In order to test what directory we are checking, you can assign this to an environment variable and check this in your script. So, for testing:

RewriteCond %{REMOTE_ADDR} ^([^.]+)\.([^.]+)\.([^.]+)\.([^.]+)$
RewriteCond %{DOCUMENT_ROOT}/%1%2%3%4-$1 (.*)
RewriteRule (.+) - [E=DIRECTORY_CHECKING_FOR:%1,L]

Examine the DIRECTING_CHECKING_FOR environment variable in your script should show something like: /home/user/public_html/2030113111-foldername, depending on your filesystem structure.

Note that %1 matches the last matched group in a preceding CondPattern (not necessarily the one immediately above if there are no matching groups). So, the %1 in the RewriteRule substitution matches the (.*) (the entire "directory name" we are checking). Whereas %1 in the RewriteCond TestString matches the first octet of the IP address.

Upvotes: 0

anroesti
anroesti

Reputation: 11403

You can use multiple RewriteConds for just one RewriteRule. Just write the RewriteConds underneath each other, e.g.

RewriteCond foo bar
RewriteCond bar foo
RewriteRule .* example.org

The RewriteRule will only execute if foo == bar and bar == foo is true (never). :)

Upvotes: 1

Related Questions