Home > OS >  How to restrict access to a specific rewrite by IP
How to restrict access to a specific rewrite by IP

Time:12-14

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

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.

CodePudding user response:

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).

  • Related