Forum Moderators: phranque
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/directory1
RewriteCond %{REQUEST_URI} !/directory2
RewriteCond %{REQUEST_URI} !/directory3
RewriteCond %{REQUEST_URI} !/directory4
RewriteCond %{REQUEST_URI} !\.php$
RewriteRule ^(.*)([^/])$ /$1$2/ [L,R=301] [edited by: engine at 2:47 pm (utc) on Sep 29, 2015]
[edit reason] please use example.com [/edit]
RewriteEngine on
# CANONICAL URL
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
#REDIRECT INDEX.PHP TO ROOT
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]
#REMOVE .PHP EXTENSION
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1/ [R=301,L]
# ADD TRAILING SLASH
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]
# INTERNALLY FORWARD (example: /dir/foo to /dir/foo.php)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
Add trailing slash on root and in directories
^(www\.example\.com)?$ RewriteCond %{THE_REQUEST} index\.php
RewriteRule ^(([^/]+/)*)index\.php http://www.example.com/$1 [R=301,L]
Always include the full protocol-plus-domain in the target to avoid a possible double redirect. The element ^.* is never necessary if you're not capturing. (Similarly .*$) Note too that you don't need the $ closing anchor after "index.php"; if you leave it out, the same rule will take care of extra stuff after the extension. If your filepaths never contain periods, you might instead express the pattern as ^([^.]+)index\.php
which is a teeny bit more efficient. (Literal periods are perfectly legal, and necessary on some sites--including apache.org itself--but it makes things a lot simpler if you don't use them.) ^([^.]+[^./])$
Anchors here are, of course, essential. ^(.*?)/?$If the request happens to end in a / slash, it will be captured. The ? can't be relied on to exclude the / slash; in fact I wouldn't use it in mod_rewrite at all. (Text editing, yes, sometimes, but it's not severe enough for situations like Apache where you have to be unambiguous.) Instead you need something like this:
^(.+[^/])/?$
Use .+ rather than .* because as already explained, requests for the root will never meet this rule.