You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在.htaccess中添加条件规则?WordPress多环境配置需求

How to Restrict S3 Upload Redirect to Only Your Production WordPress Site

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:

  1. The -z flag checks if a string is empty, which isn't what you need here—you just want to compare the host value directly.
  2. Apache uses %{HTTP_HOST} as the standard variable for the request's hostname (not req('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 RewriteCond checks 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 RewriteRule run.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:01:00