.htaccess
- Basic 301 for entire siteThis is the most basic 301 redirect for a website to a new domain/address. Put this in your .htaccess file and all URL's will be kept intact. eg: http://OldSiteAddress.com/my-example-page/ will 301 to http://NewSiteAddress.com/my-example-page/
RewriteEngine on
Redirect 301 / http://NewSiteAddress.com/
The standard 301 htaccess above can on the rare occasion affect other sites if you're on a shared hosting package with sites inside sites. For that reason this solution is stricter, and only applies if the current site url condition is met.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^OldSiteAddress\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.OldSiteAddress\.com$
RewriteRule ^(.*)$ "http\:\/\/www\.NewSiteAddress\.com\/$1" [R=301,L]
This will remove the WWW extension from your site, making it a cleaner URL.
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
If for some reason you want to show the WWW before your website URI, this .htaccess code will just do that - forcing the WWW extension for all non sub-domain requests.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]
Sometimes you will only want to 301 redirect one directory of your site (maybe /news/ for example). This 301 redirect only matches and applies if it matches the directory address you supply.
RewriteEngine on
RedirectMatch 301 /directoryname/(.*) http://NewSiteAddress.com/directoryname/$1
This will redirect every single request to a single page, useful for a 1 page website, or if you're 301'ing a whole site and not maintaining any URL's, so pushing them all to a homepage.
RewriteEngine on
RedirectMatch 301 ^(.*)$ http://www.NewSiteAddress.com
Have you switched/upgraded to SSL/HTTPS? This simple .htaccess code ensures all requests that are made to HTTP get redirected to HTTPS. It also enforces WWW, if you're already handling that, then just remove the last 2 lines.
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Enforce www:
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
Possibly you're 301'ing a section of an old site that uses a mix of php and html extensions and want to convert them now all to php extensions, this .htaccess code will do just that!
RewriteEngine on
RedirectMatch 301 /directory/(.*)\.(php|html) http://www.NewSiteAddress.com/directory/$1.php
If your site uses a common index file to handle all your url's and site content you can simply put this at the top of it to redirect all traffic to the new address.
<?php
header("Location: http://www.NewSiteAddress.com/", true, 301);
exit();
?>