Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htaccess 301 redirect folder, but not subfolders

I need to redirect from:

http://example.com/folder

to http://example.com/newfolder

But leave:

http://example.com/folder/subfolder

Where it is. Is this possible? I can't seem to make it happen without causing a heap of redirect chaos.

like image 627
Michael Watson Avatar asked Oct 26 '11 11:10

Michael Watson


6 Answers

Jestep's answer above redirects "/root-directory" but fails to redirect "/root-directory/". This can be fixed and simplified by simply:

RewriteCond %{REQUEST_URI} ^/folder/?$
RewriteRule (.*) /newfolder [R=301,L]

This will redirect "/folder" and "/folder/" but leave all sub-directories alone.

like image 84
Eaten by a Grue Avatar answered Nov 17 '22 03:11

Eaten by a Grue


I've tried other methods here with mixed success. I am no Apache expert by any means, but here is the simple one-liner that works every time for me. I just use RedirectMatch instead of Redirect and include a very simple RegEx to end the match at or just before the trailing slash, meaning that subdirectories should never qualify as a match.

RedirectMatch 301 ^/folder[/]?$ /newfolder

like image 22
Chance Strickland Avatar answered Nov 17 '22 03:11

Chance Strickland


I just ran into this and here's the solution I came up with. I prefer this method because it doesn't redirect any subdirectory.

RewriteCond %{REQUEST_URI} ^/root-directory[/]?
RewriteCond %{REQUEST_URI} !^/root-directory/+[/]?
RewriteRule (.*) http://www.example.com/ [R=301,L]
like image 41
Jestep Avatar answered Nov 17 '22 04:11

Jestep


Maybe:

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/folder[/]?
RewriteCond %{REQUEST_URI} !^/folder/subfolder[/]?
RewriteRule (.*) /newfolder/$1 [R=301,L]

This should redirect /folder to /newfolder but leave out /folder/subfolder

like image 41
Seybsen Avatar answered Nov 17 '22 04:11

Seybsen


If mod-rewrite isn't enabled or you are unable to use RewriteRule directive on your server, you can use RedirectMatch directive of mod-alias which is the default module of apache httpd server.

RedirectMatch 301 ^/folder/?$ http://example.com/newfolder/ 

This will 301 redirect /folder/ to /newfolder/ .

like image 40
Amit Verma Avatar answered Nov 17 '22 05:11

Amit Verma


Which server are you using? You could for example use mod_rewrite if you use apache and do something like this

    RewriteEngine On
    RewriteOptions Inherit
    RedirectMatch permanent ^/folder/$ http://example.com/newfolder
    #I haven't tested the above redirect btw ^ 

and put that in a .htaccess file in your /folder/ directory (assuming you can alter apache's settings, meaning you have the option AllowOverride All in that virtual host)

Here's some more info http://httpd.apache.org/docs/2.0/misc/rewriteguide.html

like image 44
cyph3r Avatar answered Nov 17 '22 03:11

cyph3r