Block Country IPs From Your Site Using htaccess

cPanel has an IP blocking mechanism to help you secure your site from individuals who you deem suspicious or malicious. This works fine for a single IP or even a handful. It is not advisable however, if you want to block an entire country using your .htaccess file.

People may want to block a country for different reasons. Some countries are more notorious for having hackers or spammers. Other people want to block a country simply because they do not do business with them. In any case, you can set the code within the htaccess file to block the IP ranges of certain countries. Follow the instructions below to perform this task.

Blocking a Country From Accessing Your Site via the .htaccess File

  1. First you will need to collect the data. You want to find a reliable list of IPs for the country you want to block. Doing a search, we find that you can get your deny list generated at IP2Location’s free visitor-blocker generator. Using this tool will let you download a text file with the code needed to block a country. In our example, we randomly chose Algeria. The output format we chose is the Apache .htaccess deny. Follow the steps to download your file.
  2. Open your file in the text editor of your choice and highlight and copy the information in the file.
  3. Next, log into your cPanel to access the .htaccess file.
  4. Find the Files category and click on the File Manager icon.
    cPanel File Manager
  5. You will then see your files listed, ensure you are set to show hidden files.
  6. Navigate to the Document Root directory for your website, locate the .htaccess file, and right-click it. This brings up a menu. Find and click on the Edit option.
    Editing the htaccess file with cPanel File Manager

  7. You are now in the File Manager file editor. Paste your code into your .htaccess file so that it forces the visitor to download that type of file. The code should be formatted similar to that below but be much longer. (Some countries like China and the US can have thousands of lines in their block code.)
    order deny,allow
    deny from 81.52.168.0/23
    deny from 188.138.10.163/32
    deny from 188.138.78.129/32
    allow from all
  8. Be sure to hit the Save Changes button in the upper right corner to save your new .htaccess configuration. Now any IP from those ranges will be denied access to your site.

71 thoughts on “Block Country IPs From Your Site Using htaccess

  1. Can you help me? I tried a lot of ways but no results…..
    also after changes in .htaccess i have an error in countries that i allow….
    I need to block all traffic from France!!!!!

    Who can help me?

    1. Hi Konstantin, while we can provide general advice on these types of settings to let you know it that they can be done, you will need to reach out to a developer for assistance on writing the exact .htaccess code for your situation. I would suggest that you start by looking up the range of IPs for various French internet service providers, but please keep in mind even this will be difficult to get working reliably. It’s usually more efficient to simply block troublesome IPs as they cause problems, or use a CMS like CloudFlare to protect from DDOS attacks.

  2. I have done the steps to block a visitors for specific country. Is there any posibility to check it, Whether it is working in the particular country from the desired country.

    1. Thanks for contacting us. You can use free online tools such as Geo Peeker and virtual private networks (VPNs) to check this. If you have a VPS, you can check cPHulk logs.

  3. Hello

    I want to block my website in India and followed the steps as described above but i am unable to achieve that.

    Please reply and help.

    Thanks

    1. I would recommend checking to ensure that you are adding these restrictions to the correct .htaccess file, in the directory of the site that you want to protect. If it is in the wrong directory it may not apply to the website you are trying to restrict India from.

  4. Hi i want block ip address and show Specific Message like : “Turn Of VPN and try again”.

    i want do this without plugin.

  5. How can I block ALL countries other than the USA rather than one at a time?  My website is really only good for services offered in one state but nothing outside of the USA.  Please let me know.

    1. Visit this third party website to download the code needed. Select United States from the list and then select “.htaccess allow” from the format options. Then click the Create ACL button. You can simply block all countries except for the US by adding the downloaded code to your .htaccess file.

  6. Hi guys! I had my hosting comany block Russia and Ukrain via .htaccess but I am still getting bombarded with attacks from these countries. Wordfence plugin keeps showing Russian cities from which attempted attacks came. Why is this happening?

    1. Lara, ultimately blocking countries via .htaccess files is not really what the file was designed for. Really, there aren’t many easy ways to block a certain country, and if there were it’s very easy to use a different IP which would completely circumvent this type of block.

  7. To the best of my understanding, you don’t need to know and block every IP address range from that country. Instead, I believe that you can use SetEnvIf to block an entire country with something like this:

    #Blocking China
    SetEnvIf GEOIP_COUNTRY_CODE CN
    BlockCountry Deny from env=BlockCountry

    Hope this helps.

    -J

    1. Hello Avinash Rughani,

      Please provide specific information in your request. We are not sure what you’re trying to block. You can use the information in the tutorial above to block countries using your .htaccess file.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  8. I don’t think using htaccess like this is a great idea. As you mentioned, some countries like China can have thousands of lines. This check will run on each and every page request, probably slowing down the site.

    Personally, I feel a much better approach is to simply outsource the job to a 3rd party provider like CloudFlare (which everyone pretty much uses anyway). Like in this tutorial: https://www.************.com/how-to-block-certain-countries-on-a-wordpress-blog/

    Those guys have specialized servers for this kind of thing. It makes sense to piggy back on their infrastructure right?

    1. You are right and we recommend CloudFlare to our customers as well. This article is for those who wish to perform this specific task for some reason.

  9. So is there another way?  I’m just curious because I have some recollection of doing something else and now I can’t remember what method that was.  Sorry I can’t remember what I did prior.  I’m a dolt…. 😛

    1. Hello Lee,

      The problem with trying to block someone is identifying WHERE they’re coming from. This is normally done by the IP address being used. I found this Blocking Website Access by Country with PHP. It still uses IP addresses, but it’s different from using the .httaccess. I hope this helps to answer your question, please let us know if you require any further assistance.

      Regards,
      Arnel C.

  10. I understand this method but for some reason I was able to block China some other way. I just don’t recall what that other way was, but it didn’t involve editing the .htaccess file. It was something that I was instructed to do via InMotion Hosting I believe.  It worked but not sure if I should try to do that method (whatever it was) or use this method. 

    1. The method mentioned above is merely the option represented here. You can certainly try it and see if it works for you.

  11. I want to know where to and how to find the IP range of a city (Delhi) to block through Htaccess or from Hosting Server

    1. Hello Vaishnav,

      In researching this question, the most plausible answer is that you can’t really block a city using only IP addresses. This is because of : proxy servers, satellite connections, and incorrect/old geolocation databases. Otherwise, you may try using a mod security rule based on a GeoIP if you’re using and Apache server.

      I hope this helps to answer your question, please let us know if you require any further assistance.

      Regards,
      Arnel C.

    1. To block a country you would need to find the entire range of IPs assigned to that country and block them.

    2. Same methodology applies here, as you would need to find the range of IPs for that specific city. Once you have the IP range, you can write a HTACCESS rule to block all the IPs so no one in the city would be able to access your website.

  12. I’ve downloaded the file from IP2Location.com in Apache 2.0 – 2.3 format but it is all one line.  Will it import into my .htaccess file OK?

    1. Hello Bruce,

      It should be fine, but if you want it to be more readable, you can paste the file into a text editor and then format for better readability. Once you’re finished, you can copy it and paste it into the .htaccess file.

      I hope that helps to answer your question! If you require further assistance, please let us know!

      Regards,
      Arnel C.

  13. If you want to block a country by TLD perhaps you would like to try:

    RewriteCond %{HTTP_REFERER} ^http?://[^/]+\.ru/? [NC] for example. Pair this with a Rewriterule, and that should accomplish the task.

     

    Cheers

    1. Hello Bert,

      Thanks for the info! Bear in mind that many people with domains will host in different countries. So, the use of this code would need to go along with the code to block country by IP. Thanks again for adding your input!

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  14. Hey Scott and other people here,

    How can I block China visiters? I have downloaded the code from

    https://www.ip2location.com/blockvisitorsbycountry.aspx  But it does not work!
     
    Would someone helping me check it out?
     
    Thanks!!!
     
    B,wishes,
    Joyce
    1. Hello Joyce,

      There is no for sure way to block a country as the IP ranges change often. Your best bet would be to stick with the ip2location list as it gets updated often.

      Best Regards,
      TJ Edens

  15. Hi,

       suppose if i wanna block my website in UAE
    Is it possible when my site open in UAE automatically show an image and in the image user can see ” This website has been blocked in UAE”

    (Image i will place in my website)
    Is it possible through htaccess. ??

    Thanks,

    Muhammad Adil
    Owner at
    Adobe Web Solution

    1. Hello Muhammad,

      You would not block the IPs then, but you would need to write a redirect code for it.

      Kindest Regards,
      Scott M

  16. Block by country code…

     

    To the banker who said they need tight control.  Buy a cisco ASA X series firewall and get firepower with it…

    1. Hello Santosh,

      Thank you for contacting us. This would typically be easier to just “allow” only the country you want to access the site.

      We are happy to help further, but will need additional details on what you are trying to accomplish.

      Thank you,
      John-Paul

  17. I have enormous problems with Indian’s stealing content and basically raping my website and republishing it on theirs without permission.

    Around 20% of my traffic came from India so when i blocked the entire country i thought i would lose 20% of my traffic.

    Actually, my traffic has increased by over 30% after blocking India because i am preventing Indians from stealing my work and ideas.

    On top of this, your site will not get as many low quality links from low authority spam sites in India.

  18. DS, What service is this as I am trying all what was recommended and nothing seems to be stopping the bot intrusion? I tried the .htaccess and the code does not stop the bot intursion from .ru or any other countries that are listed and I followed the recommended code from Scott above. Either there is something wrong with his code or preventing countires using .htaccess does not work.

    Terry

  19. After receiving several notices from the resource management team that my inmotionhosting website was using too many resources I tried many of the recommendations here about using IP deny, studying my raw logs, etc. The effort to keep my website operating without using too many resources was eating up my time and my life and still, there was always a new bot siphoning my photos and content or DDOS attempt that pushed my resources toward the limit again. I didn’t know what to do.

    Finally, I signed up for a firewall service which has the capability of blocking all countries except U.S. (or whatever) without affecting the load times, etc. That’s when inmotion resource management team told me they recommend everyone use a firewall service or something similar. I am sharing this info because in my case there didn’t seem to be any other solution for a novice user who just wants to create content and not be bothered with technical details.  Some of the things I tried here actually shut my site down entirely when I added .htaccess code incorrectly.  I hope this helps others facing similar dilemmas. 

    1. Hello Anshul,

      If you are getting spam on your website, or orders for places of which you do not perform business then it’s generally good to block those countries.

      Best Regards,
      TJ Edens

  20. I have the .htaccess set up with the recommendation from Scott and I am still see the .ru countires accessing my site even though as stated I have the following in the .htaccess file.

    RewriteCond %{HTTP_REFERER} ^https?://[^/]+\.ru/? [NC]
    Rewriterule ^(.*)$ https://www.google.com [r=307,NC]

    What am I missing and why is is not stopping the access from .ru?

    Terry

    1. Hello TD,

      Your rule is only blocking HTTPS. You need to add the rule to block HTTP as well. Copy the rule and remove the “s” out of the HTTPS and see if that doesn’t doe the trick.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  21. Hello Scott,

    The main issue is that I’m receiving a lot of visitors in China and have been trying to find a way to block this country from seeing my website (as there is a suspicion that they might be there because of my art work). I’ve looked for a way through google & the only way would be by creating .htaccess file ( never been aware of as programming is something I don’t usually use). 

    Need help in building the file ( code for blocking all ip’s that come from China) & instructions on how to upload it & where in the server with ASCII mode.

    Honestly don’t have a clue but at the same time no option as right now had to put a temporary index.html on the website to avoid from visitors accessing it.

     

    Please help, would deeply appreciate it.

     

    1. Hello Amy,

      You can use the link below which will generate a htaccess file for you.
      https://www.ip2location.com/blockvisitorsbycountry.aspx

      Best Regards,
      TJ Edens

  22. I try to understand it but no clue, 🙁 would really appreciate the help, through weekly web analysis reports I noticed that there a lot of chinese visitors on my website where is my artwork, I’ve heard they do make copies, so even though there might already be some damage, would like to block China from visiting my website any further. Is there a even easier way to this? Would appreciate it a million!

    1. Hello Amy,

      I am not aware of an easier method as of yet. Which step are you having trouble with? Perhaps we can assist you with that.

      Kindest Regards,
      Scott M

    1. Hello Paul,

      You first want to get the list of IP ranges in the US. There are a LOT. Then you simply add them in the following code:

      # ALLOW USER BY IP
      <Limit GET POST>
      order deny,allow
      deny from all
      allow from
      *list goes here*
      </Limit>

      This code says to do the DENY rule first, then the ALLOW rules. The deny says deny everyone, then the allow rule gives the exceptions.

      Kindest Regards,
      Scott M

  23. I am a bank consultant who needs really tight security on my secure subdomain.  After reading the article above, I modified my htacess file with the following lines.

    <Files *>

    Order Allow, Deny

    Allow from **.**.**.***

    Deny from all

    </Files>

    **.**.**.*** is my public ip address.

    When I do that, I get a forbidden error on my address as well.  Any ideas.

    Thanks.

    1. Hello Charlie,

      The code you have is saying to run allow rules first, then the deny rules. As the deny is Deny all, it supercedes the previous allow rule. Switching the order of them from order allw,deny to order deny,allow should allow you access from your IP. The order of the second and third lines do not matter. Below is the basic format for you.

      order deny,allow
      deny from all
      allow from 111.222.333.444

      Kindest Regards,
      Scott M

  24. Hello,

    I am trying to block certain ip numbers using the .htaccess page.  How do I create the question mark with a line under it?  This symbol is at the end of some of the ip numbers I hope to block.

    Thank you.

    1. Hello Vipo,

      Thank you for contacting us. Since .htaccess is coded in Regular expression, there should be a way or symbol available.

      We are happy to help, but it is not clear what you are looking for. Can you provide a link to an example, or some additional information.

      Thank you,
      John-Paul

  25.  

    I have noticed a couple of sites linking to my website.

     

    Semalt crawler and buttons-for-website.com 

     

    Should I block these?  I have read that some people say that I should.  If so, I understand I need to add some code to my htaccess file.  Is this true and if so what is the code and where does and were does it need to be placed within the file? 

     

    Also I did add a list of IP’s to try and deny the annoying Russian websites from cluttering up my list of external sites shown on the statistics page in my C-panel.  Is there also some code I can add to my htaccess file to stop the .ru sites from showing up in my statistics?  There are always new ones showing up every month.

     

    Thanks for your help.

     

     

     

    1. Hello Ted,

      You can block specific referrers by creating a list of them in your htacces file like this:

      <Files *>
      Order Allow,Deny
      Allow from all
      Deny from 10.1.3.0/24
      Deny from example.com
      deny from another-example.com
      </Files>

      As to blocking all sites of a tld, such as all .ru domains, you would set up a rewrite rule. Of course you would need to send it somewhere, say perhaps Google, so the below code should work for that.

      RewriteCond %{HTTP_REFERER} ^https?://[^/]+\.ru/? [NC]
      Rewriterule ^(.*)$ https://www.google.com [r=307,NC]

      Kindest Regards,
      Scott M

    1. Hello Sannu,

      Thanks for the question, but it is unclear what you are asking. In general, a website is accessible from anywhere. However, if you want to limit access, then you would need to add a mechanism that would limit access to the website. This can be done through the .htaccess file and other ways such as a firewall rule. If you want have your website accessible ONLY in the US, then you can block country IP addresses as per the article above allowing only the US. If you’re trying to do something different, then please explain your request again, with more detail.

      Kindest regards,
      Arnel C.

  26. I want don’t to index robots.txt, sitemap.xml and some specific pages of my <a href=”https://www.getpnrstatus.co.in/”>site</a> Will you tell me, how can I do it through htaccess? Any suggestion will be appreciated; thanks in advance.

    1. Hello Shawn,

      Thanks for the question. Preventing search engines from accessing your site is normally done through the robots.txt file. The only example that I found on the internet was this post. I hope this helped to answer your question! Please let us know if you have any further questions or comments.

      Regards,
      Arnel C.

  27. hi, what does the number after the slash mean?

    for example in this case “32”

    deny from 4.0.0.223/32

    thx

    rob

    1. Hello Rob,

      The 32 is part of what is called CIDR notation(Classless Inter-Domain Routing). This is used to represent a range of IP addresses. This means that the first 32 bits of the IP address given are considered significant for the network routing. Click on the link I’ve provided for a more in-depth tutorial about CIDR notation.

      If you have any further questions, please let us know.

      Regards,
      Arnel C.

  28. How do I track down the user agents of these offending IPs? I could not find that information in the AWstats. I use a plugin that lists IPs receiving 404 after attempting to login to WP. But I am not finding user agent info.

    1. Hello again DS,

      You can use the steps from my guide on how to identify and block bad robots from a website if you are on a VPS or dedicated server.

      If you have a shared hosting account, I’d recommend you create a PHP script that can run the commands for you to go through and parse User-Agents from archived raw access logs which is much easier to do then simply accessing your raw access logs and having to download them off the server for manual review.

      An example PHP script that would look for all the User-Agent strings from the domain example.com for May, which already had cPanel raw access log archiving enabled would look like this:

      userAgents.php

      <?php
      $user = $_POST[‘user’];
      $pass = $_POST[‘pass’];

      if($user == “admin”
      && $pass == “pass”)
      {
      exec (‘zgrep “May/2014” /home/userna5/logs/example.com-May-2014.gz | awk -F” ‘{print $6}’ | sort | uniq -c | sort -n > /home/userna5/userAgents’);
      echo “<p>Top User-Agents</p>”;
      echo “<pre>”;
      include(“/home/userna5/userAgents”);
      echo “</pre>”;
      }
      if(isset($_POST))
      {?>

      <form method=”POST” action=”userAgents.php”>
      User <input type=”TEXT” name=”user”></input>
      Pass <input type=”TEXT” name=”pass”></input>
      <input type=”submit” name=”submit”></input>
      </form>
      <?}
      ?>

      Please let us know if you had any other questions at all!

      – Jacob

  29. I would like to block all countries except for the US with IP deny in htaccess. Is this file size going to impact my alotted bandwidth and will it impact the wp load times? The file would be huge.

    Another approach – Is it worth considering using IP allow for just the U.S.  and deny all for anyone else, or may there be a down side to this approach? 

    1. Hello DS, and thanks for your comment.

      Adding a very large list of IP addresses to your .htaccess file can cause overhead on your site’s loading time, and it’s usually advisable to have a narrow blocking ruleset to start off with.

      Same thing for denying all traffic and then only allowing US traffic in. For example the US IP ranges downloaded from IP2Location Block Visitors by Country is about 4.4MB in size and is 167,985 line long.

      Every time a request comes into your site the .htaccess rules need to be processed. So keep in mind that a normal good visitor could have to sit and wait while the server is checking to make sure they aren’t blocked.

      In my experience many times you aren’t going to get a lot of bad traffic from a wide array of IPs within a country and need to cast such a large net. Your particular site will probably be hit by a few IP ranges here and there but you might be missing out on some legit traffic from a country you wouldn’t expect it.

      I’d recommend you use AWStats to review website stats for hosts, see which IP ranges are actually sending decent amounts of traffic to your website and then block users from your website using some .htaccess rules. You can even block by User-Agent or referer with just a few lines of code, and I’ve found this can sometime be more effective than blocking by IP address alone because if someone is attacking you they can just go through an IP address proxy, but attackers sometimes will keep the same User-Agent even while spoofing their IP address.

      Please let us know if you were having any issues with current bad traffic on your website and we’d be glad to take a look. Also let us know if you had any further questions at all!

      – Jacob

  30. I am new to this but I think I understand.  I have been entering the IP’s one by one into the Domain Deny Manager so when I looked a the htaccess file I could see my list. This has been alot of work.  Should I delete these and start fresh, or just add the list of IP’s to this list which I generated to the ones alreay there.

    Before I do this the pop up box advises I sould back up my existing file first.  Where should I do this?  Should I make a new file on the left side of the screen called BackUp and put the original in there?

    Thanks for the help.

    1. It is always a good idea to back up your files before making any changes. The easiest way to do so would be to copy the file as a different file name such as .htaccess.old.

Was this article helpful? Join the conversation!

Questions about our MailChannels Deployment? We have answers and are here to help!Learn More
+