带有重写的特定文件.htaccess的白名单IP

Here's my current situation:

I'm rewriting /api to api.php.

RewriteRule ^apidir/url/new?$ api.php [QSA,NC,L]

Now, I am whitelisting IP's for it. However, when I try and use the Files directive to block access, I can't because it is being rewritten.

<Files "\api.php">
order allow,deny
allow from all
deny from 24.11.95.151
</Files>

so, I tried just using it to block the rewritten directory

<Files "\apimashape2013/url/new">
order allow,deny
allow from all
deny from 24.11.95.151
</Files>

None of these have worked out.

If you have access to the virtualhost you can use this:

RewriteEngine on
RewriteMap hosts-deny txt:/home/youraccount/deny_list.txt
RewriteCond ${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND} !=NOT-FOUND [OR]
RewriteCond ${hosts-deny:%{REMOTE_HOST}|NOT-FOUND} !=NOT-FOUND
RewriteCond %{REQUEST_URI} ^/api [NC]
RewriteRule ^ - [F]

And have the deny_list.txt with the list of IP's or HOST you wish to blacklist:

193.102.180.41 -
bsdti1.sdm.de -
192.76.162.40 -

Read more here.


Alternatively if you don't have access to the virtualhost, you can change the name of your php file to something unique for example thisismyapi.php and use it like this:

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

<Files "thisismyapi.php">
order allow,deny
allow from all
deny from 24.11.95.151
</Files>

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !thisismyapi.php
RewriteRule ^api/?(.*)$ /api/thisismyapi.php [L]

Why do I change it to other name?

Because this way it will match it anywhere it is so it should work just fine for your needs and will not conflict with other files.

For example in this way it the file was named index.php it would conflict with index.php in other folders.

Not sure why the first <Files> container isn't working. The \ shouldn't have any effect. But the container needs to be in the directory or parent directory of where the api.php file is.

Alternatively, you can include this in your htaccess:

RewriteCond %{REMOTE_ADDR} ^24\.11\.95\.151$
RewriteRule ^/?api.php$ - [L,F]