You can use something like this code in your DOCUMENT_ROOT/.htaccess
file:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www\.)?subdomain\.com$ [NC]
RewriteCond ${ipmap:%{REMOTE_ADDR}} !^(127\.0\.0\.1|192\.168\.|10\.|1\.2\.3\.4)$
RewriteRule ^ - [F]
Source: answer from anubhava on Stack Overflow
You can also allow specific IP addresses and deny the rest with this:
order deny,allow
allow from 31.24.232.14
allow from 127.0.0.0
allow from 192.168.0.0
deny from all
These might also help:
<If "%{HTTP_HOST} != 'www.example.com'">
Redirect / http://www.example.com/
</If>
There's a good chance this last one is what you want. If the code works, it will detect that the website loaded is not example.com
(but your subdomain). And if it's your subdomain it will block all IP addresses except the one that you list in the allow from.
<If "%{HTTP_HOST} != 'www.example.com'">
order deny,allow
allow from 31.24.232.14
allow from 127.0.0.0
allow from 192.168.0.0
deny from all
</If>
You could also try:
<If "%{HTTP_HOST} = 'subdomain.example.com'">
order deny,allow
allow from 31.24.232.14
allow from 127.0.0.0
allow from 192.168.0.0
deny from all
</If>
For Apache 2.4+
If you're going to use require ip
, you may need to do it like this:
Require all denied
Require ip 123.123.123.123
Read more: https://stackoverflow.com/questions/37865658/htaccess-allow-deny-ip-using-require-apache-2-4
Maybe this works?:
<If "%{HTTP_HOST} = 'staging.example.com'">
Require all denied
Require ip 123.123.123.123
</if>
Sources are also showing that you need RequireAny
to allow only specific IPs. If that's the case you may have to modify it for your subdomain requirement condition:
<RequireAny>
Require ip 1.2.3.4
Require ip 23.34.45.56
</RequireAny>