Skip to content

🐛 fix(rewrite,redirect): anchor rules to the start of the path#4483

Merged
ReneWerner87 merged 3 commits into
gofiber:mainfrom
0xghost42:fix/4476-rewrite-redirect-start-anchor
Jul 1, 2026
Merged

🐛 fix(rewrite,redirect): anchor rules to the start of the path#4483
ReneWerner87 merged 3 commits into
gofiber:mainfrom
0xghost42:fix/4476-rewrite-redirect-start-anchor

Conversation

@0xghost42

Copy link
Copy Markdown
Contributor

Description

The rewrite and redirect middlewares build each rule's regex by replacing * with (.*) and appending $, but never anchor the start of the path. Without a leading ^ the pattern matches any suffix, so a rule fires on unrelated routes:

  • rewrite rule /users/* also rewrites /api/users/1.
  • redirect rule /old also redirects /very/old (a request gets redirected by a rule whose path it only happens to end with).

This anchors both ends (^...$) so a rule matches the whole path. The middlewares already appended $, so the intent was a full-path match; only the start anchor was missing.

Fixes #4476

Changes introduced

  • middleware/rewrite: prepend ^ when compiling each rule regex.

  • middleware/redirect: prepend ^ when compiling each rule regex.

  • Regression tests in both packages: a rule matches from the start (/users/1 -> rewritten, /old -> redirected) but no longer fires on a path that merely ends with the rule (/api/users/1, /very/old). Both new tests fail on main and pass with this change.

  • Benchmarks: No benchmark changes; the existing rule-matching benchmarks are unaffected (one extra anchor character per compiled rule, no per-request cost).

  • Documentation Update: None required; this corrects behavior to match the existing $-anchored intent and the echo middleware it is based on (which anchors at the start).

  • Changelog/What's New: Bug fix - rewrite/redirect rules now anchor to the start of the path.

  • Migration Guide: A rule that previously relied on suffix matching will no longer fire mid-path; such matches were unintended (the reported bug).

  • API Alignment with Express: No public API change.

  • API Longevity: No signature or config change; behavior only.

  • Examples: Covered by the new tests.

Type of change

  • Code consistency (non-breaking change which improves code reliability and robustness)

Checklist

  • Conducted a self-review of the code and provided comments for the anchoring rationale.
  • Added unit tests to validate the fix (with fail-on-main confirmation).
  • Ensured that new and existing unit tests pass locally (go test ./middleware/rewrite/... ./middleware/redirect/...).
  • gofmt and go vet clean.

Note: I also flagged in the issue that rule strings are not escaped before compilation (regex metacharacters in a rule like /v1.0/* are interpreted as regex). I kept this PR to the anchoring fix to stay minimal; happy to address escaping in a follow-up if wanted.

Rule regexes appended $ but never prepended ^, so a pattern matched any
suffix of the path. A rule then fired on unrelated routes (e.g. /users/*
also rewrote /api/users/1, and /old also redirected /very/old). Anchor
both ends so a rule matches the whole path. Adds regression tests for both
middlewares.

Closes gofiber#4476
@0xghost42 0xghost42 requested a review from a team as a code owner June 30, 2026 10:32
@ReneWerner87 ReneWerner87 added this to v3 Jun 30, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Jun 30, 2026
@coderabbitai

coderabbitai Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 98d039f7-7922-4483-b775-fd6f54f45acd

📥 Commits

Reviewing files that changed from the base of the PR and between 7987082 and a00f337.

📒 Files selected for processing (2)
  • middleware/redirect/redirect_test.go
  • middleware/rewrite/rewrite_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • middleware/rewrite/rewrite_test.go
  • middleware/redirect/redirect_test.go

Walkthrough

Both redirect and rewrite middlewares now anchor compiled rule regexes with ^ at the start and $ at the end, so rules only match full paths. New tests cover the anchored behavior for both middlewares.

Changes

Redirect and Rewrite start-anchor fix

Layer / File(s) Summary
Anchor regex patterns in redirect and rewrite
middleware/redirect/redirect.go, middleware/rewrite/rewrite.go
Rule pattern compilation now wraps each regex as ^...$ instead of appending only $.
Tests verifying start-anchor behavior
middleware/redirect/redirect_test.go, middleware/rewrite/rewrite_test.go
Test_Redirect_StartAnchor and Test_Rewrite_StartAnchor verify that matching no longer occurs on suffix-only paths.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

🐇 I hopped to the left, then hopped to the right,
With ^ at the start, the paths fit just right.
No sneaky suffix can fool the new line,
Full-path matches now behave by design.
Hooray for the regex, crisp and true!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: anchoring rewrite and redirect rules at the start of the path.
Description check ✅ Passed The description is mostly complete and covers the bug, fix, linked issue, change list, and type of change.
Linked Issues check ✅ Passed The changes match #4476 by adding start anchors in both middlewares and adding regression tests for the intended behavior.
Out of Scope Changes check ✅ Passed The PR stays focused on anchoring and test coverage, with no clearly unrelated code changes.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@middleware/redirect/redirect_test.go`:
- Around line 136-163: Add t.Parallel() as the first statement in
Test_Redirect_StartAnchor so the new redirect test follows the repository’s Go
test concurrency requirement. Locate the test by its name in redirect_test.go
and update it without changing the existing assertions or setup.

In `@middleware/rewrite/rewrite_test.go`:
- Around line 178-211: Add t.Parallel() at the start of Test_Rewrite_StartAnchor
to match the repo’s test concurrency requirement for new Go tests. Update the
test function in rewrite_test.go so it calls t.Parallel() immediately after the
function begins, before creating the Fiber app or setting up rewrite rules.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4ab63607-d237-42de-8691-b562a387b1f9

📥 Commits

Reviewing files that changed from the base of the PR and between e0edc7d and 7987082.

📒 Files selected for processing (4)
  • middleware/redirect/redirect.go
  • middleware/redirect/redirect_test.go
  • middleware/rewrite/rewrite.go
  • middleware/rewrite/rewrite_test.go

Comment thread middleware/redirect/redirect_test.go
Comment thread middleware/rewrite/rewrite_test.go
@gaby gaby changed the title fix(rewrite,redirect): anchor rules to the start of the path 🐛 fix(rewrite,redirect): anchor rules to the start of the path Jul 1, 2026
@codecov

codecov Bot commented Jul 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.90%. Comparing base (3f26054) to head (a00f337).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #4483   +/-   ##
=======================================
  Coverage   92.90%   92.90%           
=======================================
  Files         138      138           
  Lines       13595    13595           
=======================================
  Hits        12631    12631           
  Misses        597      597           
  Partials      367      367           
Flag Coverage Δ
unittests 92.90% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Repo requires t.Parallel() at the start of added Go tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@ReneWerner87 ReneWerner87 merged commit 7800359 into gofiber:main Jul 1, 2026
17 checks passed
@welcome

welcome Bot commented Jul 1, 2026

Copy link
Copy Markdown

Congrats on merging your first pull request! 🎉 We here at Fiber are proud of you! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

@github-project-automation github-project-automation Bot moved this to Done in v3 Jul 1, 2026
@ReneWerner87 ReneWerner87 modified the milestones: v3, v3.4.0 Jul 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

🐛 [Bug]: rewrite/redirect rules match anywhere in the path (missing start anchor)

3 participants