Apache 2.4 – Restrict URL Access to Certain IPs

301-redirectapache-2.4iprestriction

I am trying to restrict a specific URL to be available outside the network only to specific IP addresses.
When a user outside tries to access that URL and not from the list of IPs he should be redirected to the homepage.

This is what I've tried so far without any luck.
The last part it redirects everyone to the homepage regardless of IP.

<Location "/secret">
#    <If "%{REMOTE_ADDR} != -ipmatch '123.123.123.123/255.255.255.255'">
#    Redirect 303 "/secret" /
#    </If>

RewriteCond "%{REMOTE_ADDR}" "!123\.123\.123\.123"
RewriteRule .* / [R,L]

LogLevel debug rewrite:trace6
</Location>

PS: the /secret URL is in fact a virtual URL and does not exist physically on the drive.

Best Answer

Use Require [ip|host|env] to specify who has access to your vhost or location.

    <Directory "/docroot">
        Require ip 10.10.11.12
    </Directory>   

When it comes to redirecting, think about a custom error page. This is much more general, because every unauthorized access should provoke a 403 error and thus can be evaluated easily.

I never did this with apache, but use this strategie with nginx. For apache something like this should do:

ErrorDocument 403 http://homepage.example.com

Custom error documents are configured using the ErrorDocument directive, which may be used in global, virtualhost, or directory context. It may be used in .htaccess files if AllowOverride is set to FileInfo. (from the apache docs)

Related Topic