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

如何在.htaccess正则表达式中使用Apache预定义环境变量

Solution to Dynamic CORS Origin Matching Using Apache Environment Variables

Since you’ve already set SetEnv domain_zone com in your Apache config, the key fix here is swapping out the basic SetEnvIf directive for SetEnvIfExpr. The standard SetEnvIf doesn’t support referencing environment variables directly in its regex pattern, but SetEnvIfExpr leverages Apache’s expression syntax to dynamically build your match rule using the pre-defined domain_zone variable.

Here’s the updated .htaccess code that ties everything together:

<FilesMatch "\.(js|css|ttf|otf|eot|woff|ico)$">
  # Dynamically match Origins ending with .website.{domain_zone}
  SetEnvIfExpr "req('Origin') =~ m#http(s)?://(.*\.website\.%{ENV:domain_zone})$#" AllowOrigin=%{req:Origin}
  # Set the CORS header only if the Origin was validated
  Header add Access-Control-Allow-Origin %{AllowOrigin}e env=AllowOrigin
</FilesMatch>

Key Breakdown:

  • SetEnvIfExpr: This directive uses Apache’s expression language, which lets you pull environment variables with %{ENV:variable_name}. We insert %{ENV:domain_zone} directly into the regex to replace the hardcoded .com, making the rule environment-agnostic.
  • req('Origin'): Grabs the actual Origin header from the incoming request, which we then match against our dynamic pattern.
  • Exact Origin instead of *: Setting AllowOrigin to the request’s actual Origin is more secure than using a wildcard *, and it avoids issues with credentialed requests (like those with cookies) that are blocked when * is used for Access-Control-Allow-Origin.

Environment Flexibility:

  • When your Apache config uses SetEnv domain_zone com, the regex automatically becomes http(s)?://(.*\.website\.com)$—matching all *.website.com subdomains just like your original code.
  • For a staging environment with SetEnv domain_zone dev, the regex adjusts to http(s)?://(.*\.website\.dev)$ without any changes to .htaccess.

Just ensure you have these Apache modules enabled (they were already required for your original setup):

  • mod_setenvif (powers SetEnvIfExpr)
  • mod_headers (handles setting the CORS header)

内容的提问来源于stack exchange,提问作者Ievgen Baziak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:48:59