I'm having a bit of trouble figuring out something that should be simple. I want to 301 redirect everything in a directory to one single file in a new location.
In my .htaccess
, I've already tried the following...
Redirect 301 /myDir/ http://www.mydomain.com/myNewDir/index.html
and this...
Redirect 301 /myDir/ http://www.mydomain.com/myNewDir/
and this...
Redirect 301 /myDir http://www.mydomain.com/myNewDir
The problem is that each of those are simply mapping each file within /myDir/
, and appending it to the end of the destination URL.
After Googling, I saw something that said to do this...
Redirect 301 ^/myDir(.*) http://www.mydomain.com/myNewDir
But that just does the same thing... it's mapping the existing file location to the end of the URL.
It was easy finding lots of ".htaccess redirect" tutorials online but they seem to only show the obvious examples like 'one-to-one file mapping' or 'one-to-one directory mapping'. These tutorials also seem to neglect explaining the various relevant file directives and how to properly use them.
This particular hosting account is garbage and also has FrontPage extensions installed. Mod-rewrite fails (breaks the whole site) yet the Redirect 301
lines are operating fine. So until I can move this new (non-FrontPage) site to a more robust hosting account, I'll need to stick with the Redirect 301
one-liner.
How can I simply use a Redirect 301
to redirect everything within /myDir/
to the same single file located at /myNewDir/index.html
? (I'd prefer using just /myNewDir/
if possible). Kindly explain, in detail, the file directives used in your solution.
UPDATE:
Previously accepted answer is not working.
Example:
RedirectMatch 301 /myDir1/(.*) http://mydomain.org/newpath/myDir1/index.html
...is giving a "Too many redirects occurred trying to open" error.
This is because /myDir1/(.*)
is matching anyplace within the string so if the target URL contains /myDir1/
anywhere, not just the root, it will get redirected into a nasty loop.
See my own posted answer for correct solution.
I found the answer within one of my old projects.
Redirect 301
is all wrong for this. I really wanted RedirectMatch 301
instead.
RedirectMatch 301 ^/myDir/(.*) http://www.example.com/myNewDir/
Explanation(s):
http://httpd.apache.org/docs/1.3/mod/mod_alias.html#redirectmatch
"This directive is equivalent to
Redirect
, but makes use of standard regular expressions, instead of simple prefix matching."
http://www.zytrax.com/tech/web/regex.htm
"The
^
(circumflex or caret) outside square brackets means look only at the beginning of the target string, for example,^Win
will not findWindows
in STRING1 but^Moz
will findMozilla
."
and...
"The
.
(period) means any character(s) in this position, for example,ton.
will findtons
,tone
andtonneau
but notwanton
because it has no following character."
and...
The
*
(asterisk or star) matches the preceding character 0 or more times, for example,tre*
will findtree
(2 times) andtread
(1 time) andtrough
(0 times).