How to restrict users from accessing the Yii 2 app based on their IP address


We have hosted Yii 2 basic application on shared hosting server. We want to restrict access to the application from users based on their IP address.

If we use .htaccess which blocks the IP address listed, will it be feasible? As the IP addresses changes over time.

Can we use some code in the .htaccess file or the index.php file which checks the IP address is belonging to some country and some state, then only allow that user to access the application otherwise show forbidden message.

Which method is suitable listing all the IP address in the .htaccess file to block or use some code in either .htaccess or index.php to check the IP address is from the allowed country and state using some geo location service?

Have you forgotten you asked the same question about three weeks ago and had being answered?

Did you try to do anything with it by yourself?

Yes, I used .htaccess to allows only IP addresses of country that need to access. But as I searched on the google and found that the IP addresses change over time. So this might not be the feasible solution

So can we use some code using PHP in Yii2 that checks the IP address of the user accessing the application. We can get the country code, city name from that IP address using some relevant and reliable geo IP location service or API and then allow the user to access the application otherwise restrict them. Can we do it in .htaccess or index.php?

How to geolocate an IP address in .htaccess?

I would have a base controller for all your customer controllers filtering access to any action using access filters:

Create a rule targeting all actions and denying access to all IP adresses you have collected.

Ok, I was thinking to use geo ip enabled in the .htaccess

GeoIPEnable On
RewriteEngine on
RewriteRule (index).php$ - [F,L]