Forum Moderators: phranque

Message Too Old, No Replies

301 redirect for entire directories using .htaccess

What is the best way to redirect directories using .htaccess

         

riospace

9:30 pm on Oct 17, 2006 (gmt 0)

10+ Year Member



Can anyone show me an example of the proper way to do a 301 redirect of an entire directory to a new directory using .htaccess?

What I want to do in the example below is redirect everything in directories 2&3 to directory 1 and get rid of the extra directories.

example.com/directory_1/directory_2/

example.com/directory_1/directory_3/

I just want: example.com/directory_1/

FromRocky

12:58 am on Oct 18, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)\.htaccess$ - [F]

RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,NC]

RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^directory_1/directory_2/(.*)$ http://example.com/directory_1/$1 [R=301,NC]

RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^directory_1/directory_3/(.*)$ http://example.com/directory_1/$1 [R=301,NC]

riospace

3:02 am on Oct 18, 2006 (gmt 0)

10+ Year Member



Thanks.

I actually want www.example.com. I should have added the www in my example. Would this work or if I am way off please set me straight:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)\.htaccess$ - [F]

RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^directory_1/directory_2/(.*)$ http://www.example.com/directory_1/$1 [R=301,NC]

RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^directory_1/directory_3/(.*)$ http://www.example.com/directory_1/$1 [R=301,NC]

jdMorgan

5:10 am on Oct 18, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



All you really need to solve the problem stated in your first post is just the two rules:

RewriteRule ^directory_1/directory_2/(.*)$ http://www.example.com/directory_1/$1 [R=301,L]
RewriteRule ^directory_1/directory_3/(.*)$ http://www.example.com/directory_1/$1 [R=301,L]

The domain canonicalization logic need not enter into this.

Jim

g1smd

11:01 pm on Oct 18, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



FromRocky: Your code unwittingly produces a redirection chain for some URLs - a double redirect.

If you still need to redirect non-www to www then do that redirect after jdMorgan's example code, as his code includes the correct destination URL in the redirect.