403Page Labs Home

HOW TO: Use Cloudflare to reverse proxy a subdirectory

12 March, 2020

What is this for?
You have a requirement to serve a complete site through a “subdirectory” (ie. /news or /blog) without being able to move it “physically” to a subdirectory on your root domain’s server.

Head to the Workers page in your Cloudflare account and click Launch Editor:

On the newer dashboard layout, click Create a Worker and then Quick Edit. Add the following snippet into the Script box:

addEventListener('fetch', event => {
  var url = new URL(event.request.url);
  if (url.pathname.startsWith('/news/') || url.pathname === '/news') {
    handleBlog(event, url);
  } else {

async function handleBlog(event, url) {
  var originUrl = url.toString().replace(

Swap the slug or “subdirectory” (in this case it’s news), as well as your desired user-facing domain (in this case it’s https://403page.com/news) and the source domain (in this case it’s https://403.NEWS.SITE.COM.

Once you click Save, your subdirectory will now serve the site from the source (visiting https://403page.com/news will show you the content from https://403.new.site.com.

If you’re using WordPress on the source install, you’ll want to change the RewriteBase line in your .htaccess to:


…in the case above it would be RewriteBase /news/. Here’s what it should look like with a default .htaccess:

You’ll also want to modify your home and siteurl values so they can be set by WordPress dynamically. You can do this by adding these lines in your wp-config.php (again, on the source install):

define('WP_SITEURL', 'https://' . $_SERVER['SERVER_NAME']);
define('WP_HOME', 'https://' . $_SERVER['SERVER_NAME']);

NOTE: Cloudflare allows for up to 100,000 worker requests per 24 hours and 5,000 requests per 10 minutes on a free plan. Check out their pricing after that here.

More fun Cloudflare worker stuff:

HOW TO: Use Cloudflare to enable Basic Auth on a subdirectory

HOW TO: Use Cloudflare to handle Country-based redirects

HOW TO: Block non-Cloudflare requests to your site with a Worker

HOW TO: Support .webp on Cloudflare’s edge with a Worker

HOW TO: Create a downtime failover for your site with a Cloudflare Worker