Question

How to Allow Only Cloudflare IPs to Access My FastAPI Server on DigitalOcean?

Hi, I have an HTTP server built with Python and FastAPI. I’m receiving a lot of malicious requests trying to access paths like /.env and /.git.

Previously, when I was using AWS ECS, I was **able **to block these kinds of requests by allowing only Cloudflare’s reserved IP ranges. That way, only requests coming through my domain (which is on Cloudflare) were able to reach the server—everything else was blocked at the firewall level, and it worked perfectly.

Now I’ve moved to DigitalOcean, and I’m still using Cloudflare for my domain. I want to implement the same setup: only allow requests that come from Cloudflare IPs and reject all others. How can I properly configure this so that I’m sure all traffic goes through Cloudflare?

“Note: I’m using DigitalOcean’s App Platform, the serverless one.”

Thanks in advance!


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

alexdo
Site Moderator
Site Moderator badge
April 3, 2025

Heya, @e6317acc26184445891017fc7a2d90

You can add a middleware in your FastAPI app that checks the request IP and blocks anything not coming from Cloudflare.

Cloudflare publishes their IP ranges here: https://www.cloudflare.com/ips/

Update these regularly or automate syncing them if needed. Also in Cloudflare DNS make sure your domain and subdomains are proxied (orange cloud ☁️ ON). Disable “Development Mode” too, as it bypasses the proxy.

Hope that this help!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.