Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to restrict access to a specific rewrite by IP

I have a website that I’m dynamically creating URLs for with htaccess rewrites. What I’m looking to do is restrict a URL based on the IP address of those accessing it.

For example, I’m trying to restrict access to any rewrite in the XYZ "sub-folder"

These should all be restricted to a specific IP    
www.domain.com/XZY
www.domain.com/XZY/anotherfile.html
www.domain.com/XZY/anotherfolder

But no restriction to any other rewrite

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

These should all be accessible    
www.domain.com/ABC
www.domain.com/greatfile.html
www.domain.com/ABC/greatfolder

The XYZ folder does not actually exist so placing an htaccess file in there isn’t an option for me. I appreciate any assistance you can provide.

>Solution :

Using mod_rewrite, respond with a 403 Forbidden for any requested URL that starts /XZY and is not from the stated IP address:

RewriteEngine On

RewriteCond %{REMOTE_ADDR} !=203.0.113.111
RewriteRule ^XZY($|/) - [F]

Any blocking directive like this need to go near the top of the .htaccess file, before any existing rewrites.

NB: This assumes the client is connecting directly to your application server. However, if you are using a CDN (eg. Cloudflare), load balancer or front-end caching proxy then you may need to check another element of the request since the client is not connecting directly with your server (the proxy is).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading