7

mod_rewrite always baffles me... can anyone tell me the rules I need to get the following clean URLs? Desired URL on the left, real URL on the right.

/our-work/ => /our-work.html
/our-work/some-project/ => /our-work/some-project.html
/contact/ => /contact.html

As you can see, I want to force trailing slashes on all URLs too.

Thanks!

JJJ
  • 32,902
  • 20
  • 89
  • 102
Alistair Holt
  • 1,432
  • 3
  • 17
  • 28

1 Answers1

10

Try this rule:

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)/$ $1.html [L]

And for adding trailing slashes:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .*[^/]$ %{REQUEST_URI}/ [L,R=301]

Make sure to put those rules that cause an external redirect (explicitly using R flag or implicitly) in front of those rules that just cause an internal redirect/rewrite. So in this case:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .*[^/]$ %{REQUEST_URI}/ [L,R=301]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)/$ $1.html [L]
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • Thanks. That works for the top level /our-work/ example but ends up redirecting me to URLs like /redirect:/our-work/some-project.html.html.html/ when I'm hitting URLs with two levels like /our-work/some-project/. I should also say that I'm using this on a localhost URL at the moment with the ports specified. – Alistair Holt May 14 '10 at 18:11
  • Just tested in another environment, crazy redirect URL was a problem from somewhere else, no idea where. Your solution is perfect thanks! – Alistair Holt May 14 '10 at 18:22
  • 1
    @alistair.mp: Ah, you’re right. I’ve added a condition that tests whether the rewrite will be point to an existing file to avoid infinite recursion. – Gumbo May 14 '10 at 18:30