---
type: "Source File"
title: "\"\"\""
description: "\"\"\" Trailing-slash canonicalisation for the CopeCheck Flask sites. Problem ------- Flask/Werkzeug only auto-redirects in ONE direction. A rule declared WITH a trailing slash (\"/foo/\") redirects \"/foo\" -> \"/foo/\" with a."
resource: "https://layoffs.copecheck.com"
tags: ["copecheck", "layoffs", "source-file", "py"]
timestamp: "2026-09-26T08:14:59Z"
site: "layoffs"
source_path: "copecheck-layoffs/slash_canonical.py"
---

# """

Source path: `copecheck-layoffs/slash_canonical.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-26T08:14:59Z`

```py
"""
Trailing-slash canonicalisation for the CopeCheck Flask sites.

Problem
-------
Flask/Werkzeug only auto-redirects in ONE direction. A rule declared WITH a
trailing slash ("/foo/") redirects "/foo" -> "/foo/" with a 308. A rule
declared WITHOUT one ("/foo") does NOT redirect "/foo/" -> it returns 404.

Nearly every CopeCheck route is declared without a trailing slash, so every
canonical page on the network 404s when a visitor, crawler or pasted link
adds a slash.

Fix
---
A `before_request` hook that issues a permanent 301 to the canonical
(slash-less) form, but ONLY when:

  * the request is a safe method (GET/HEAD),
  * the requested path actually ends in "/" and is not the site root,
  * the slashed form does NOT match any registered rule, and
  * the slash-less form DOES match a registered rule.

That last pair of conditions is what keeps this safe. It never touches a
route that legitimately owns the slashed form (those keep working exactly as
before), it never invents a redirect to a page that does not exist, and it
never serves the same content at two URLs - the slashed URL always 301s to
the single canonical one, so no duplicate URLs are created.

Query strings are preserved. Non-safe methods (POST to an API endpoint, for
example) are deliberately left alone, since redirecting them would drop the
request body.

Idempotent: installing twice on the same app is a no-op.
"""

from flask import redirect, request
from werkzeug.exceptions import MethodNotAllowed, NotFound
from werkzeug.routing import RequestRedirect

_FLAG = "[redacted]"


def install_slash_canonicaliser(app):
    """Attach the canonicaliser to `app`. Safe to call more than once."""
    if getattr(app, _FLAG, False):
        return app
    setattr(app, _FLAG, True)

    @app.before_request
    def _canonicalise_trailing_slash():
        if request.method not in ("GET", "HEAD"):
            return None

        path = request.path
        if path == "/" or not path.endswith("/"):
            return None

        stripped = path.rstrip("/")
        if not stripped:
            return None

        adapter = app.url_map.bind(
            request.host,
            script_name=request.script_root or "/",
            url_scheme=request.scheme,
        )

        # If the slashed form is already a real route (or Werkzeug already
        # wants to redirect it somewhere), leave it entirely alone.
        try:
            adapter.match(path, method=request.method)
            return None
        except RequestRedirect:
            return None
        except (NotFound, MethodNotAllowed):
            pass
        except Exception:
            return None

        # Only redirect if the slash-less form is genuinely routable.
        try:
            adapter.match(stripped, method=request.method)
        except Exception:
            return None

        target = stripped
        if request.query_string:
            target += "?" + request.query_string.decode("utf-8", "replace")
        return redirect(target, code=301)

    return app
```
