Skip to main content

plain.redirection

Database-driven URL redirects with logging and admin interface.

Overview

You can manage URL redirects through the database instead of hardcoding them in your URL configuration. When a request results in a 404, the RedirectionMiddleware checks for a matching redirect rule and sends the user to the new location.

from plain.redirection.models import Redirect

# Create a simple redirect
Redirect.query.create(
    from_pattern="/old-page/",
    to_pattern="/new-page/",
    http_status=301,  # Permanent redirect (default)
)

All redirects are logged automatically, and 404s that don't match any redirect are logged separately. You can view and manage everything through the built-in admin interface.

Creating redirects

The Redirect model stores your redirect rules. Each redirect has a from_pattern to match against and a to_pattern to redirect to.

# Temporary redirect (302)
Redirect.query.create(
    from_pattern="/sale/",
    to_pattern="/promotions/summer-sale/",
    http_status=302,
)

# Disable a redirect without deleting it
redirect = Redirect.query.get(from_pattern="/old-page/")
redirect.enabled = False
redirect.save()

When multiple redirects could match, you can control priority with the order field. Lower values are checked first.

# This redirect is checked first
Redirect.query.create(
    from_pattern="/blog/featured/",
    to_pattern="/featured-posts/",
    order=10,
)

# This more general pattern is checked later
Redirect.query.create(
    from_pattern="/blog/",
    to_pattern="/articles/",
    order=20,
)

Regex patterns

For dynamic URL patterns, set is_regex=True and use regex groups in your patterns.

# Redirect /blog/2024/01/my-post/ to /posts/2024-01-my-post/
Redirect.query.create(
    from_pattern=r"^/blog/(\d{4})/(\d{2})/(.+)/$",
    to_pattern=r"/posts/\1-\2-\3/",
    is_regex=True,
)

The to_pattern can reference captured groups from the from_pattern using \1, \2, etc.

Full URL matching

By default, patterns match against the request path (e.g., /old-page/). If your pattern starts with http, it matches against the full URL including the domain and query string.

# Redirect requests from a specific domain
Redirect.query.create(
    from_pattern="https://old-domain.com/page/",
    to_pattern="/page/",
)

Logs

Every redirect is recorded in RedirectLog, capturing the original URL, destination, and request metadata like IP address, user agent, and referrer.

from plain.redirection.models import RedirectLog

# Recent redirects
recent = RedirectLog.query.all()[:10]

for log in recent:
    print(f"{log.from_url} -> {log.to_url} ({log.ip_address})")

Requests that result in 404s (and don't match any redirect) are logged in NotFoundLog.

from plain.redirection.models import NotFoundLog

# Find 404s from a specific referrer
broken_links = NotFoundLog.query.filter(referrer__contains="external-site.com")

Automatic cleanup

Logs are automatically cleaned up by the DeleteLogs chore. See Settings for configuring retention.

Admin interface

The package includes admin views for managing redirects and viewing logs. Once installed, you will find three sections under "Redirection" in your admin:

  • Redirects - Create, edit, and delete redirect rules
  • Redirect logs - View successful redirects with request details
  • 404 logs - Monitor URLs that resulted in 404s

The 404 logs are useful for discovering broken links on your site. You can search the logs to find patterns and create redirects to fix them.

Settings

Setting Default Env var
REDIRECTION_LOG_RETENTION_TIMEDELTA timedelta(days=30) -

See default_settings.py for more details.

FAQs

How does the middleware decide when to redirect?

The middleware only checks for redirects when a request results in a 404. It iterates through enabled redirects (ordered by the order field, then by creation date) and returns the first match. If no redirect matches, the 404 is logged and the original response is returned.

Can I redirect to external URLs?

Yes. The to_pattern can be any URL, including external sites:

Redirect.query.create(
    from_pattern="/partner/",
    to_pattern="https://partner-site.com/landing/",
)

What HTTP status codes can I use?

Any valid HTTP redirect status code works. The most common are:

  • 301 - Permanent redirect (default). Search engines update their index.
  • 302 - Temporary redirect. Search engines keep the original URL.
  • 307 - Temporary redirect that preserves the request method.
  • 308 - Permanent redirect that preserves the request method.

Installation

Install the plain.redirection package from PyPI:

uv add plain.redirection

Add plain.redirection to your INSTALLED_PACKAGES in app/settings.py:

# app/settings.py
INSTALLED_PACKAGES = [
    # ...other packages
    "plain.redirection",
]

Add the middleware to your MIDDLEWARE setting. It should be near the end so other middleware can process requests first:

# app/settings.py
MIDDLEWARE = [
    # ...other middleware
    "plain.redirection.RedirectionMiddleware",
]

Run migrations to create the database tables:

plain migrate

You can now create redirects through the admin interface or programmatically using the Redirect model.

Metadata

Release files for plain.redirection 0.34.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for plain.redirection 0.34.0
File Size Uploaded Provenance Actions
plain_redirection-0.34.0.tar.gz 12.5 kB Without provenance Details for plain_redirection-0.34.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for plain.redirection 0.34.0
File Interpreter ABI Platform Actions
plain_redirection-0.34.0-py3-none-any.whl Python 3 none any Details for plain_redirection-0.34.0-py3-none-any.whl

Total release size: 30.0 kB

Release files / plain_redirection-0.34.0.tar.gz

Download URL plain_redirection-0.34.0.tar.gz
Size 12.5 kB
Tags Source
SHA-256 checksum
How to use checksums
eb335d86aade9dc4dd44feca74c2e5ea4f94ff0e66efc1318c1c97a91bae5343
BLAKE2b-256 checksum
How to use checksums
28bf8c509833ad92fb0b000d1acebb9dfd60a5578539b5f93f86ae87f5fb3e18
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.1 {"installer":{"name":"uv","version":"0.11.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / plain_redirection-0.34.0-py3-none-any.whl

Download URL plain_redirection-0.34.0-py3-none-any.whl
Size 17.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
eb92954c27bfd9a80c2f36acdaf3e684c7cd60b3443fcb0ddb7788f3f220c3d7
BLAKE2b-256 checksum
How to use checksums
7a17003c3ed3b82bd17ee83ed7f062d4ed103ea5c3696f9dbfd27c8d48748566
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.1 {"installer":{"name":"uv","version":"0.11.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for plain.redirection 0.34.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.34.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page