Take the 2-minute tour ×
Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

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
add comment

1 Answer

up vote 2 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

http://forum.modrewrite.com/viewtopic.php?f=4&t=4627

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

share|improve this answer
add comment

Your Answer

 
discard

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.