Removing index.html with mod_rewrite in .htaccess
It's quite easy to remove index.html from a URL with mod_rewrite. Let's say we want to redirect www.ewallhost.com/index.html to www.ewallhost.com:
RewriteEngine On RewriteRule ^index\.html$ / [R=301,L]
Here's a brief explanation, if you're not familiar with .htaccess syntax:
- The RewriteRule directive has three parts, a pattern (^index\.html$), asubstitution (/) and optionally some modifiers ([R=301,L]).
- In the pattern: the symbol ^ means "start with", and the symbol $ means "ends with". Also, the backslash is the escape character, and we need to put it in front of the dot, because the dot normally has a special meaning, and we don't want that here. So in this case the pattern will only match the string "index.html".
- If the pattern is found (that is, if the request is to index.html), it will be redirected to "/", which is the root of your website.
Always remove index.html
What if you want to always remove index.html? For example, www.ewallhost.com/host/index.html -> www.ewallhost.com/host/ . Easy!
RewriteEngine On RewriteRule ^index\.html$ / [R=301,L] RewriteRule ^(.*)/index\.html$ /$1/ [R=301,L]
The second rewrite rule checks for any request that ends with /index.html, and removes the index.html bit. Again, quick explanation of the second rewrite rule:
- (.*) - This means 'anything'. The dot means 1 character, and the asterisk means "zero or more". So, "zero or more characters". We put this between parentheses because we'll need this in the substitution (keep reading).
- In the substitution, $1 means "whatever was between parenthesis in the pattern", which is anything before the /index.html .
Sorted! You might need little adjustments if you have more specific needs, but hopefully this gives you a good starting point.
3 Users Found This Useful