1

I have tried all means to do a 301 redirect from blog.example.org to https://www.example.com/post using .htaccess but the redirect doesn't seem to be working.

I'm using this code below;

RewriteEngine On
RewriteRule ^blog/(.*)$ https://www.example.com/post$1 [L,R=301]

Kindly someone share with me what I could be doing wrong.

  • 1
    You've stated you want to redirect from blog.example.org, yet you are trying to match this with the regex ^blog/(.*)$? Do you have a /blog subdirectory? Your problem description suggests are are wanting to redirect a single URL to another single URL, however, your code implies a multi-URL to multi-URL redirect from a subdirectory? Please clarify. (Also, test with 302 redirects to avoid caching issues during testing.) – MrWhite Apr 12 at 19:08
  • Do the two hosts blog.example.org and www.example.com point to the same filesystem, or different? – MrWhite Apr 12 at 19:24
2

To change a sub-domain, I use the ServerAlias and a condition against the HTTP_HOST.

For example, I generally wanted to have "", "w", "ww", "wwww" redirect to "www". I do this using the following type of rules:

ServerName www.example.com
ServerAlias example.com w.example.com ww.example.com wwww.example.com
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(example.com|w.example.com|ww.example.com|wwww.example.com)$
RewriteRule ^/(.*) https://www.example.com/$1 [R=permanent,L]

So you could also change a blog.example.com to a www.example.com. If you prefer to not have any sub-domain, then you can use (see the blog.example.com?):

ServerName example.com
ServerAlias w.example.com ww.example.com www.example.com wwww.example.com blog.example.com
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(w.example.com|ww.example.com|www.example.com|wwww.example.com|blog.example.com)$
RewriteRule ^/(.*) https://example.com/$1 [R=permanent,L]

Note that in Apache2 you could also write two entries to avoid the RewriteCond. For example, a <VirtualHost> that looks like this:

ServerName w.example.com
ServerAlias ww.example.com www.example.com wwww.example.com blog.example.com

would not match example.com so you do not need to have the RewriteCond since you want to redirect all sub-domain to example.com.

This does not work in an .htaccess file, though since that's already past the <VirtualHost> point which is too late.

Note: answered as per your question, although as MrWhite says, you're not 100% clear about what fails on your end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.