Webmasters Stack Exchange is a question and answer site for pro webmasters. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Here is an example from the Apache documentation for enforcing canonical hostnames:

RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) http://www.example.com/$1 [L,R,NE]

What I would like to know is why the /? is needed. I've tried removing it and everything appears to work the same. I was under the impression that the pattern part of the rewrite rule was compared against what comes after the slash.

share|improve this question
up vote 3 down vote accepted

The {REQUEST_URI} string starts with a / character. Apache changed regex engines when it changed versions, so Apache version 1 requires the leading slash while Apache 2 forbids it! We can satisfy both versions by making the leading slash optional with the expression ^/? (? is the metacharacter for zero or one of the preceding character).

Source: http://www.sitepoint.com/apache-mod_rewrite-examples/

A few more resources which talk about the leading slash


and http://net.tutsplus.com/tutorials/other/a-deeper-look-at-mod_rewrite-for-apache/

share|improve this answer
But the Apache 2.2 documentation has multiple examples with a leading ^/ . E.g. the RewriteCond section has: RewriteRule ^/$ /homepage.std.html [L]. Is that a documentation bug? – Matthew Flaschen May 2 '14 at 2:36
It turns out (as I just tested) that the leading / (^/) is required, at least in VirtualHost context. I did not test other contexts. – Matthew Flaschen May 2 '14 at 2:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.