Forum Moderators: phranque

Message Too Old, No Replies

Edit .htaccess to prevent site access unless in subfolder

         

ocon

12:05 am on Feb 4, 2010 (gmt 0)

10+ Year Member Top Contributors Of The Month



Hello

I have one website accessible through two different domains. Both domain names point to the same hosting folder.

example.com
notexample.com

I want to change my .htaccess file so example.com is fully functional, but any access to notexample.com returns a 404 error unless trying to access notexample.com/wp-admin*

Is this possible?

g1smd

7:42 am on Feb 4, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Yes it is, but if notexample.com is indexed you might be better off with a 301 redirect to begin with to preserve traffic coming from searchengines.

You'll need a RewriteCond to check if the path begins with "not admin", another to check the domain, and a RewriteRule to either rewrite to a non-existant path (to trigger the 404 error) or else send the 301 response to the correct URL.

If you decide on the redirect route, easier code would be just a single negative-match RewriteCond for "not admin" needed to be added before your standard domain canonicalisation rule.

ocon

2:16 pm on Feb 4, 2010 (gmt 0)

10+ Year Member Top Contributors Of The Month



Thanks for the reply.

notexample.com is not indexed, or even currently setup right now, and I don't want it to have any association with example.com, so the 404 path would suit me well.

So, what I'm looking for would be like this:

RewriteCond %{HTTP_HOST} ^(www\.)?notexample\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/wp-admin.* [NC]
RewriteRule ^(.*) /doesnt_exist [L]

Of note, I made the check for the domain name first because only I would even access this domain name. And since everyone else would be accessing example.com and not in the wp-admin, would it be more efficient to have that check first?

jdMorgan

4:35 pm on Feb 4, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It would be most efficient to make use of the RewriteRule's pattern-matching, since it can test the requested URL-path. The RewriteCond won't even be evaluated unless the RewriteRule pattern matches (See Apache mod_rewrite documentation). Do not end-anchor your hostname pattern unless you include regex to match FQDN-format hostnames and/or hostnames with appended port numbers -- e.g. "^(www\.)?notexample\.com(\.|\.?:[0-9]+)?$"

RewriteCond %{HTTP_HOST} ^(www\.)?notexample\.com [NC]
RewriteRule !^wp-admin/ /path-which-does-not-exist [L]

On Apache 2.x and above, you could use:

RewriteCond %{HTTP_HOST} ^(www\.)?notexample\.com [NC]
RewriteRule !^wp-admin/ - [R=404,L]

Jim