Removing trailing slash and redirecting html

Jeremy picture Jeremy · Jun 30, 2012 · Viewed 9.4k times · Source

The problem I'm having is that the first URL works and the second one doesn't.

http://www.example.com/podcast/episode1
http://www.example.com/podcast/episode1/

Is there a way to redirect all trailing slash versions to the non-trailing slash version?

The problem is even worse here, since neither of these work:

example.com/podcast
example.com/podcast/

Only this one works:

example.com/podcast.html

and I do not want the html extension visible.

Here's the code I have in my .htaccess file so far:

#shtml

AddType text/html .html
AddHandler server-parsed .html

#html

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

#index redirect

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.html\ HTTP/ 
RewriteRule ^index\.html$ http://example.com/ [R=301,L]

#non www to www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Can you help me out?

Answer

Scott Stevens picture Scott Stevens · Jun 30, 2012

Removing the trailing slash is easy. Removing the .html isn't.

Removing the slash

Just R=301 redirect if you see a slash on there.

RewriteRule ^(.*)/$ $1 [R=301]

Don't add the L flag since you want to continue processing this request. Also make it the first rule.

Why you can't remove the .html

Your issue is that once page becomes page.html (via the internal redirect), a new request for page.html is given to the server. So then your .htaccess will see the request for page.html and redirect to page. Cue infinite loop.

Optimising your code

  1. You only need RewriteEngine On once at the top of your .htaccess
  2. You should add the www redirect to the top of your code and remove the L flag (see Removing the Slash)