Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect all urls exactly, just change domain name

Tags:

I have a website with roughly 1K URLs. The website is moving to a different domain name. The URLs will be the exact same though, otherwise. I'd like to incorporate an htaccess or some kind of rule that does a 301 redirect for all URLs in one fell swoop. It would essentially replace the domain name as a 301 redirect.

Example:

  • Current URL: domain.example/blog/post-1.html
  • Redirect To: newdomain.example/blog/post-1.html

And that performed as a 301 redirect. How would I do that?

like image 565
hdwebpros Avatar asked Nov 06 '13 15:11

hdwebpros


2 Answers

Place this redirect rule in your DOCUMENT_ROOT/.htaccess file of domain.com:

RewriteEngine On  RewriteCond %{HTTP_HOST} ^(?:www\.)?domain\.example$ [NC] RewriteRule ^ http://newdomain.example%{REQUEST_URI} [L,R=301,NE] 

Details:

  • Condition RewriteCond %{HTTP_HOST} ^(?:www\.)?domain\.example$ matches when host name in request is either www.domain.example or domain.com.
  • RewriteRule redirect all the URLs to newdomain.example with the URI exactly same as in the original request.
  • R=301 sets HTTP status code to 301 (permanent redirect)
  • NE is for no escaping to avoid encoding of special characters (if any) from original requests
  • L is for last rule
like image 153
anubhava Avatar answered Nov 23 '22 08:11

anubhava


When moving a domain name to a new domain where the only change to the url is the domain name, I use the following redirect in my Apache .htaccess file

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

This ensures that all links in the old site are redirected and search engines like Google, Bing etc. are aware that the domain was permanently moved. This has the benefit that any ranking from domain.com is transferred to newdomain.example. Make sure not to include a / after the domain in the rewrite rule or it will double-up.

This is an alternative to the method shown above.

like image 34
Clinton Avatar answered Nov 23 '22 09:11

Clinton