Semantic URLs for static HTML files with .htaccess and mod_rewrite

mod_rewrite always puzzles me ... can someone 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 slashes to all URLs as well.

Thanks!

+7
.htaccess mod-rewrite clean-urls
source share
1 answer

Try the following rule:

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

And to add slashes:

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

Be sure to place these rules that cause an external redirect (explicitly using the R flag or implicitly) in front of these 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] 
+10
source share

All Articles