I have a need to temporarily redirect my website to a static version hosted on Cloudflare. The current site is a WordPress site hosted at Ionos and WordPress seems to be doing a 301 redirect from mydomain.com
to www.mydomain.com
. I would like to be able to continue to access the WordPress instance by going to www.mydomain.com
but if I (or anyone else) goes to mydomain.com
I would like to be redirected to static.mydomain.com
.
I put this in my .htaccess
file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^mydomain.com
RewriteCond %{HTTP_HOST} !^www.mydomain.com
RewriteRule ^(.*) https://static.mydomain.com/$1 [R=302,L]
</IfModule>
However, when I visit mydomain.com
I'm still redirected to www.mydomain.com
so it seems the .htaccess RewriteRule isn't getting triggered and so WordPress is doing its redirect.
Is there some way in .htaccess (I don't have access to the Apache configuration file) to force a redirect like I'm describing?
Best Answer
I'm assuming the static version of your site (at
static.example.com
) is literally a static non-WordPress site so cannot itself account for any redirects.There's nothing actually "wrong" with your rule as posted. However, ...
The previous "WordPress" 301 (permanent) redirect from non-www to www will have been cached (persistently) by the browser (and possibly intermediary) cache. This will need to be manually cleared for your redirect in
.htaccess
to have any effect.Your redirect must go at the top of the
.htaccess
file before the WordPress code block (rewrite to the front-controller), ie. before the# BEGIN WordPress
comment marker. If you place the redirect at the end of the file (or after the WordPress code block) it will only be processed for requests to static resources (and directories). WordPress (virtual) URLs will not be redirected, since the request has already been rewritten toindex.php
(the WordPress front-controller).Aside:
Just a bit of a tidy up... you don't need to repeat the
RewriteEngine On
directive, since this already appears later in the file, in the WordPress code block.You do not need the
<IfModule>
wrapper. This redirect must occur, it's not optional.The second condition (
RewriteCond
directive) is not required. There's no need to check that theHost
isA
and notB
. (If it'sA
then it can't possibly beB
as well.)So, the above could be simplified to: