如何在.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
*: SettingAllowOriginto 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 forAccess-Control-Allow-Origin.
Environment Flexibility:
- When your Apache config uses
SetEnv domain_zone com, the regex automatically becomeshttp(s)?://(.*\.website\.com)$—matching all*.website.comsubdomains just like your original code. - For a staging environment with
SetEnv domain_zone dev, the regex adjusts tohttp(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(powersSetEnvIfExpr)mod_headers(handles setting the CORS header)
内容的提问来源于stack exchange,提问作者Ievgen Baziak
相关产品推荐
相关产品推荐

