Mona Abdelmajeed
Mona Abdelmajeed

Reputation: 686

htaccess: redirect to subdomain if page not found

Here's description for my problem

i have moved the site from this path

http://www.site.com/any-thing-here-workfine

To subdomain like this

http://portal.site.com/any-thing-here-workfine

But to now , google has my previous links and all this links are down

So i'm working now to move this down links from www to sub domain if this page return notfound

Mean

My links in google still

http://www.site.com/any-thing-here-workfine this page notfound

so i want to redirect it 301 to same url but like thia

http://portal.site.com/any-thing-here-workfine

How can i do this ?

Upvotes: 0

Views: 2737

Answers (1)

Tom McClure
Tom McClure

Reputation: 6739

This is pretty straightforward for mod_rewrite

RewriteEngine On
RewriteCond %{HTTP_HOST} =www.site.com [NC]
RewriteRule ^/?(.*) http://portal.site.com/$1 [R=301]

That will redirect everything. But what if you post some new content at www.site.com and you don't want that to redirect?

If you just have static content at www.site.com then it's easy. Just add a "404" test for the file/folder that does not exist.

RewriteEngine On
RewriteCond %{HTTP_HOST} =www.site.com [NC]
# 404 test -- file/folder exists?
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*) http://portal.site.com/$1 [R=301]

However, if you have some new "virtual" URLs at www.site.com that don't correspond directly to files on the filesystem, then you will have to figure out how to filter these out of your redirect rule (otherwise you will get false-positives in your 404-test). Say for example, the virtual content at www.site.com, that shouldn't redirect, all starts with /newsite/... then you'll end up with something like this:

RewriteEngine On
RewriteCond %{HTTP_HOST} =www.site.com [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/?newsite/
RewriteRule ^/?(.*) http://portal.site.com/$1 [R=301]

Upvotes: 4

Related Questions