Mobile app version of vmapp.org
Login or Join
Rivera981

: Htaccess redirect subfolder to root 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

@Rivera981

Posted in: #Htaccess

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 ^(.*)$ %1/ [R=301,L]

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

RedirectMatch 301 ^/store/$ 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?

10.02% popularity Vote Up Vote Down


Login to follow query

More posts by @Rivera981

2 Comments

Sorted by latest first Latest Oldest Best

 

@Pierce454

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'>

10% popularity Vote Up Vote Down


 

@Ann8826881

RedirectMatch 301 ^/store/$ 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_HOST}/ [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$ / [R=301,L]

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme