How to redirect full url to subdomain

.htaccess301-redirectredirect

I am trying to redirect a site page to a subdomain (same url) with .htaccess but it's stuck in a redirect loop or redirected to 404 page. The following is my code used in .htaccess:

RewriteRule ^uk.example.com/2-day-course.html http://www.example.com/2-day-course.html [L,R=301,NC]

Some of the URLs need to be redirected from subdomain to main domain on the same page, it has the same issue like above.

Is there a way to do it with .htaccess file?

Best Answer

If this is resulting in a redirect loop then I assume uk.example.com and www.example.com must be pointing to the same place. You need to explicitly check the host before redirecting:

RewriteCond %{HTTP_HOST} ^uk\.example\.com [NC]
RewriteRule ^2-day-course\.html$ http://www.example.com/2-day-course.html [L,R=301,NC]

Note that the RewriteRule pattern matches against the URL-path only. This does not include the hostname, which must be checked in a separate condition.

As always with 301 redirects, you'll need to clear all caches before testing.

Related Topic