Apache htaccess RewriteRule to remove trailing slash; infinite loop

.htaccessapache-2.2mod-rewriteregexrewrite

I use the following in .htaccess (mod_rewrite) to remove the trailing slash from my URLs:

RewriteRule ^([a-z0-9_-]+)/$ $1 [L,NC,R=301]

Of course, since the character class doesn't match a slash, this works fine for links like some_page/, but not article/some_page/.

If I add a slash to the character class to make [a-z0-9_/-], I get an infinite loop when trying to load the page. I also tried making the + non-greedy by using +?, but that didn't work either; neither did removing the R=301 redirect.

(If it makes a difference, the page to load, /article/some_page/ is actually /article/some_page/index.html, I just want it to appear as /article/some_page.)

Best Answer

If it makes a difference

Yes it does. Apache (mod_dir) will send back a redirect if you pass a URL that maps to a directory without a trailing '/', e.g.

[colinm@example ~]$ curl -I http://localhost/somedir
HTTP/1.1 301 Moved Permanently
Date: Mon, 24 Oct 2011 11:48:37 GMT
Server: Apache/2.2.3 (Red Hat)
Location: http://localhost/somedir/
Content-Type: text/html; charset=iso-8859-1
Related Topic