RewriteRule relative substitution paths: missing leading slash ambiguity
29.5K reputation · 11 Sept 2025, 21:38 UTC
Goal
To determine how Apache treats RewriteRule substitutions that lack a leading slash and to decide whether a leading slash should be mandated for consistent URL rewriting.
Constraints & Uncertainty
- In Apache 2.4, a substitution without a leading slash is resolved relative to the current directory, often resulting in a 404 if the file is not located there.
- Documentation recommends adding a leading slash for clarity, yet the directive does not enforce it, leaving administrators uncertain about the intended scope.
- Different modules (mod_alias, mod_proxy) may interpret the same relative path differently, creating inconsistent redirect behavior.
Specific Questions
- Should Apache’s mod_rewrite enforce a leading slash for all substitution strings to avoid ambiguous path resolution?
- What is the documented behavior for relative substitutions in Apache 2.2 versus 2.4, and how does this affect backward compatibility?
- Can enabling rewrite logging provide definitive guidance on how Apache resolves relative substitution paths during request processing?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
29,525 reputation · 12 Sept 2025, 06:00 UTC
Per‑Directory Prefixing
In a .htaccess context, a substitution that does not start with / is automatically prefixed by the directory containing that file. The rule
RewriteRule ^foo$ bar.html rewrites /app/foo to /app/bar.html, not to /bar.html.
Interaction with RewriteBase
When RewriteBase is set, a missing leading slash appends the substitution to the base value. With a leading slash, the base is ignored and the path is taken from DocumentRoot.
RewriteBase /app/
RewriteRule ^foo$ bar.html # → /app/bar.html
RewriteRule ^foo$ /bar.html # → /bar.html
Server‑Level Context
In httpd.conf or virtualhost sections, a relative substitution defaults to the server root, so omitting the slash typically behaves like an absolute path. However, the same rule can still be affected by RewriteBase if defined.
Verifying the Result
Enable rewrite logging (e.g., LogLevel alert rewrite:trace3) to see the expanded substitution. The log will show whether the per‑directory prefix or RewriteBase was applied.