问题原文
原帖链接 · Darrell Brogdon · CC BY-SA 4.0
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?
已采纳解答
原帖链接 · MrWhite · CC BY-SA 4.0
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
.htaccessto have any effect.Your redirect must go at the top of the
.htaccessfile before the WordPress code block (rewrite to the front-controller), ie. before the# BEGIN WordPresscomment 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:
<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>
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 the Host is A and not B. (If it's A then it can't possibly be B as well.)
So, the above could be simplified to:
# Temporarily redirect domain apex to "static" subdomain
RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule (.*) https://static.example.com/$1 [R=302,L]
# BEGIN WordPress
: Other directives follow....
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
