Bobby's Blog

Enable CloudFlare DDoS Protection Automatically


CloudFlare offers a free DDoS protection and they have a cool API that you could use to enable and disable their DDoS protection easily.

I’ve decided to write a short bash script which would enable and disable this for your website automatically if needed.

Please note that this is mainly an example. The script can be modified based on your needs and on your server hardware power. You can feel free to contact me for an advice if you wish.

Before following this guide here, please setup your CloudFlare account and get your website ready. If you are not sure how to do that you can follow these steps here: Create a Cloudflare account and add a website

Once you have your CloudFlare account and once your website is routed though CloudFlare you can follow the steps here:

  • Make sure curl is installed on your server:

curl --version

If curl is not installed you need to run the following:

  • For RedHat/CentOs

yum install curl

  • For Debian/Ubuntu

apt-get install curl

  • Create a working directory

mkdir ~/cloudflare

  • We are now going to create the scripts that would actually hookup with the API and would enable/disable the DDoS protection. We would need a few things, which you could get from your CloudFlare account:
  1. Your Zone ID
  2. Your API key
  3. The email address associated with the API key

Once you have this information create the following files with the following content:

  • This file would be used to disable the DDoS protection

vim ~/cloudflare/

  • Add the following and update the information accordingly:

  • Create a second file which would be used to enable the DDoS protection

vim ~/cloudflare/

  • Add the following and update the information accordingly:

Now we are ready to get the script up and running. Please note that you would need to update some values accordingly. Simply read the comments : )

vim ~/cloudflare/

Now add executable permissions:

chmod +x ~/cloudflare/

Now that we have the script in place all you need to do is to add a cron job that would trigger the script every 30 seconds for example, the cron should look something like:
crontab -e

This is pretty much it, please test the script before adding the cron job. If you get any errors, please feel free to send me an email.

About the author


Linux System Administrator