Hi markpines
!
Thanks for reaching out on the Cloudflare Community.
There are a couple ways you might block access to a particular subdomain in this case:
- Create a Firewall Rule to block access to blog.mysite.com
- Issue a Blocked response for requests to that subdomain from the Worker itself
Option 1: Firewall Rule
You can create a Firewall Rule which simply blocks any requests to a given subdomain, by matching on the Hostname field.
You can find Firewall Rules under the Firewall tile on the navigation bar at the top:
There are two advantages to using Firewall Rules to block these requests:
- Firewall Rules trigger before Workers, so these requests won’t count against your allotted Worker requests because they are blocked before the Worker triggers.
- Your users will be presented with a standard Cloudflare error page - on the Pro plan or higher you can even customize these error pages to your liking from the Custom Pages tile.
Option 2: Issue block response from the Worker
In this option, you can add a block of code to the Worker itself, which will issue a 403 response to the client.
Using your example, this code might look something like the following (starting from the beginning of your existing snippet):
addEventListener('fetch', event => {
console.log(`Received new request: ${event.request.url}`)
var url = new URL(event.request.url);
if (url.hostname.startsWith('blog') { // Check if the hostname starts with "blog"
return new Response("Blocked Host", { status: 403 }) // Generate and return a 403 Forbidden response
}
else if (url.pathname.startsWith('/blog/')
...
// The rest of your code follows as before...
...
This will just issue a 403 Forbidden response to the browser with the text “Blocked Host”.
The advantage to this method is you can fully customize the response issued by the Worker to your liking.
Instead of issuing a 403 you might, for example, also want to simply redirect requests from blog.mysite.co
to https://www.mysite.co/blog
or the desired location - this might be a smoother user experience than simply blocking them, but it depends on your use case.
DISCLAIMER: THIS SOFTWARE IS PROVIDED BY CLOUDFLARE “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CLOUDFLARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.