How could I block access from visitors from certain countries to a file on my site (xyz.com/thisFile.php)?

StackOverflow https://stackoverflow.com/questions/7621945

Question

I need to block visitors from certain countries from uploading images - but they should be able to access the site.

For e.g. I've a site xyz.com. The way I have it set up currently, all visitors from blacklisted countries are unable to access the site itself, and are greeted with a 403. This isn't a good solution, of course, so I want to set it up such that these users can still access and play around with the site, but NOT be able to upload images (which is through clicking on xyz.com/upload/ which is an alias for xyz.com/upload_file.php). Every other user from other whitelisted countries should obviously be able to use all of the site's functionalities, save for users from blacklisted countries, who should not be able to upload their images.

How could I ensure this is the case through .htaccess? I am currently on Cloudflare, and the relevant text in .htaccess is as follows:

SetEnvIf CF-IPCountry AA UnwantedCountry=1
SetEnvIf CF-IPCountry BB UnwantedCountry=1
SetEnvIf CF-IPCountry CC UnwantedCountry=1
Order allow,deny
Deny from env=UnwantedCountry
Allow from all

Thanks.

Was it helpful?

Solution

Change those lines of code in your question with this:

<Files "upload_file.php">
SetEnvIf CF-IPCountry AA UnwantedCountry=1
SetEnvIf CF-IPCountry BB UnwantedCountry=1
SetEnvIf CF-IPCountry CC UnwantedCountry=1

Order allow,deny
Allow from all
Deny from env=UnwantedCountry
</Files>

This will restrict access to those countries only to the file upload_file.php.

OTHER TIPS

Does it have to be an alias? Could you just create an upload/ folder, and put the .htaccess in there? It might require changing some of the upload_file.php logic, but that seems like the easiest fix to me.

I think .htaccess files can be put into /any/ subdirectory. Move your file uploading code into a directory and put .htaccess controls there?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top