能否在.htaccess中添加条件规则?WordPress多环境配置需求
Absolutely, this is totally feasible—your goal is completely achievable, and the issue was just a syntax error in your original <If> condition. Let's break down the fix step by step.
What Went Wrong With Your Initial Condition
Your original <If "-z req('Host') == 'www.<PRODUCTION>.com/'"> had two critical issues:
- The
-zflag checks if a string is empty, which isn't what you need here—you just want to compare the host value directly. - Apache uses
%{HTTP_HOST}as the standard variable for the request's hostname (notreq('Host')), and this value never includes a trailing slash.
Solution 1: Use Apache 2.4+ <If> Directive (Cleanest Approach)
If your server runs Apache 2.4 or newer, the <If> directive is the cleanest way to wrap your rule. Here's the corrected code:
<If "%{HTTP_HOST} == 'www.<PRODUCTION>.com'"> RewriteRule ^wp-content/uploads/(.*)$ https://s3-eu-west-1.amazonaws.com/<BUCKET-NAME>/wp-content/uploads/$1 [R=301,L] </If>
%{HTTP_HOST}pulls the exact hostname from the request (e.g.,www.yourprod.com).- The condition only triggers the rewrite rule when the request hits your production domain—your staging site will ignore this block entirely.
Solution 2: Use RewriteCond (Compatible With Older Apache Versions)
If you're stuck on Apache 2.2 or earlier (which doesn't support <If>), use a RewriteCond to add a pre-condition to your rule:
RewriteCond %{HTTP_HOST} ^www\.<PRODUCTION>\.com$ RewriteRule ^wp-content/uploads/(.*)$ https://s3-eu-west-1.amazonaws.com/<BUCKET-NAME>/wp-content/uploads/$1 [R=301,L]
- The
RewriteCondchecks if the hostname matches your production domain (note the escaped dots\.—since dots act as wildcards in regex, we need to escape them to match literal dots). - Only when this condition is satisfied will the following
RewriteRulerun.
Critical Testing Tip
Before deploying with [R=301] (permanent redirect), test with [R=302] (temporary redirect) first. Browsers cache 301 redirects aggressively, so using a 302 lets you tweak things without clearing browser cache if something goes wrong. Once you confirm it works as expected, switch back to 301.
内容的提问来源于stack exchange,提问作者Sylar

