Reputation: 55
I have a domain (example.com
) and I want to load a page from this subdomain (subdomain.example.com
) within an iframe. But I want to block direct access to the subdomain with .htaccess
. So I have edited the .htaccess
in the subdomain with the code below.
There I have added access only to the localhost, but it doesn't work. It gives me page error. How can I solve this?
RewriteEngine On
#RewriteCond %{HTTP_HOST} ^(www\.)?subdomain.myurl.com$
#--allowed ip(s)--#
#RewriteCond %{REMOTE_ADDR} !^(127.0.0.1)$
#RewriteRule ^ - [F,L]
Upvotes: 0
Views: 1944
Reputation: 45829
You can't reliably do this with .htaccess
. The problem here is that when the browser requests the subdomain's URL in the IFRAME, this is also essentially a "direct request" - a direct request from the client. So, from the server's perspective, it's difficult to determine whether the request is from within the iframe or not.
The closest you can get is to check the HTTP Referer request header (as sent by the browser), which should be set to example.com
when the document in the IFRAME is requested. However, this is unreliable, can be easily faked and will block indexing - if that is a concern. If a user types the URL directly in the browser's address bar then there is no HTTP Referer, but likewise,
the Googlebot also does not send a Referer header.
For example, in the root of the subdomain:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https?://(subdomain\.)example\.com
RewriteRule ^ - [F]
If the HTTP Referer is not start http://example.com
or http://subdomain.example.com
(HTTP or HTTPS) then block the request (403 Forbidden).
The L
flag is not required when using the F
flag - it is implied.
Alternatively, you could perhaps use JavaScript to detect whether the document is contained in a frame or not and if not, redirect to the framed document. However, this would only work if you have a single "master" document that contains the IFRAME.
There I have added access only to the localhost
The IP address from which the request originates has nothing to do with whether the subdomain is being requested from within an IFRAME on the main domain.
Upvotes: 1