How to redirect an old site to a new domain with rewrite rules

In this example we show how to redirect all the pages from an old website and domain to a new one or redirect only some selected pages or how to redirect only the main website page ...

Home Programming Examples Other Examples → How to redirect an old site to a new domain with rewrite rules
how to redirect an old site to a new domain with rewrite rules


In the example below, we'll consider how to redirect all pages from an old website and a domain to a new one or how to
redirect just some particular pages or only the main page of the website.

In general when we would like to redirect a page from an old site to a new one, we can use the following rewrite rule -


RewriteEngine On
RewriteRule ^old-page-url$ https://www.newdomain.com/new-page-url [R=301,L]


or to redirect only the main page of a website using the .htaccess file, you can use the following code:


RewriteEngine On
RewriteRule ^$ https://www.newdomain.com/new-page [R=301,L]


So we are using the Apache's mod_rewrite module to enable the rewriting engine and then with -

RewriteEngine On - we enable the rewriting engine for the current directory and its subdirectories.

RewriteRule ^$ https://www.newdomain.com/new-page [R=301,L] - in this case, ^$ is a regular expression that matches the empty string, representing the main page. https://www.newdomain.com/new-page is the URL you want to redirect to.

[R=301] indicates a 301 redirect, which means "Moved Permanently." You can change it to [R=302] for a temporary redirect if needed.

[L] means "Last" and tells Apache to stop processing further rules if this one matches. It's usually added at the end of the rule.

And finally if you want to redirect an entire domain or all pages within a directory to a new domain, you can use the following code:


RewriteEngine On
RewriteCond %{HTTP_HOST} ^old-domain.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.old-domain.com$ [NC]
RewriteRule ^(.*)$ http://new-domain.com/$1 [R=301,L]




See More ExamplesHire Me For A Project






 
Connect with meLinkedIn ProfileFacebook Profile


2024 © SofiaCoder.com
×

Programming ExamplesPHP ExamplesMySQL ExamplesJavaScript ExamplesHTML ExamplesCSS ExamplesNode.js ExamplesOther Home PageSofia Coder LinkedIn ProfileSofia Coder Facebook Profile