3

In the following scenario, example.com is my homepage.

I need to:

  • redirect www to non-www

  • redirect index.html to homepage

  • redirect example.com/store to example.com

This is my htaccess code

# Switch rewrite engine on
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

# Do index.html to root redirect
RewriteCond %{THE_REQUEST} ^.*/index.html
RewriteRule ^(.*)index.html$ http://%{HTTP_HOST}/$1 [R=301,L]

RedirectMatch 301 ^/store/$ http://example.com

This seems to work except it only redirects example.com/store/ (with forward slash after store) to the homepage. It does not redirect example.com/store (without forward slash)

Any ideas how I can fix this?

2
RedirectMatch 301 ^/store/$ http://example.com

it only redirects example.com/store/ (with forward slash after store)

Which is exactly what the "forward slash after store" is saying in your RedirectMatch pattern. However, you should not mix RedirectMatch (mod_alias) with RewriteRule (mod_rewrite) redirects. Different modules execute at different times, so the outcome can be unexpected.

So, instead, with mod_rewrite:

RewriteRule ^store$ / [R=301,L]

This assumes there are no other URLs that start /store.

(Although, do you want to redirect all requests for files in that subfolder as well? ie. /store/some-file.php to /some-file.php? ... However, the pattern in your example ^/store/$, which you said "seems to work", also prevents this.)


# Do index.html to root redirect
RewriteCond %{THE_REQUEST} ^.*/index.html
RewriteRule ^(.*)index.html$ http://%{HTTP_HOST}/$1 [R=301,L]

Bit of an aside, but you also need to escape the . (literal dot) in index.html. ie. /index\.html in both the RewriteCond and RewriteRule directives. Also, the ^.* at the start of your RewriteCond pattern is superfluous and can simply be removed. You also don't really need to specify an absolute URL in the substitution (although some do argue that this can avoid potential pitfalls later). So, this becomes:

RewriteCond %{THE_REQUEST} /index\.html
RewriteRule ^(.*)index\.html$ /$1 [R=301,L]
-1

Why not create example.com/store/imdex.php and have one line of code

header("Location:../index.html");

Or if for some odd reason you can't create a php script, do a meta refresh

   <meta http-equiv='refresh' content='0;url=http://example.com'>
  • 1
    I would not suggest meta refreshes though, not good for search engines. – Max Jul 6 '15 at 7:43
  • Bit harsh, there was no mention of search engines in the original question, just how could it be done. This is one way. – Steve Jul 7 '15 at 7:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.