---
title: Rewrite links on HTML pages · Cloudflare Rules docs
description: Dynamically rewrite links in HTML responses. This is useful for site migrations and branding updates.
lastUpdated: 2024-11-29T14:20:18.000Z
source_url:
  html: https://77261bbd.preview.developers.cloudflare.com/rules/snippets/examples/rewrite-site-links/index.md
  md: https://77261bbd.preview.developers.cloudflare.com/rules/snippets/examples/rewrite-site-links/
---

```js
export default {
    async fetch(request) {
        // Define the old hostname here.
        const OLD_URL = "oldsite.com";
        // Then add your new hostname that should replace the old one.
        const NEW_URL = "newsite.com";


        class AttributeRewriter {
            constructor(attributeName) {
                this.attributeName = attributeName;
            }
            element(element) {
                const attribute = element.getAttribute(this.attributeName);
                if (attribute) {
                    element.setAttribute(
                        this.attributeName,
                        attribute.replace(OLD_URL, NEW_URL),
                    );
                }
            }
        }


        const rewriter = new HTMLRewriter()
            .on("a", new AttributeRewriter("href"))
            .on("img", new AttributeRewriter("src"));


        const res = await fetch(request);
        const contentType = res.headers.get("Content-Type");


        // If the response is HTML, it can be transformed with
        // HTMLRewriter -- otherwise, it should pass through
        if (contentType.startsWith("text/html")) {
            return rewriter.transform(res);
        } else {
            return res;
        }
    },
};
```
