问题原文
原帖链接 · Kal · CC BY-SA 4.0
Using Apache 2.4.29 and looking to set some headers if the URL contains specific term (api).
Here is my attempt I set in the config file
RewriteEngine On
RewriteCond %{REQUEST_URI} api ENV=SIGN2
Header set "Access-Control-Allow-Origin" "*" env=SIGN2
Header set "Access-Control-Allow-Headers" "*" env=SIGN2
I also tried:
SetEnvIf REQUEST_URI ".*api.*" SIGN
Header set Access-Control-Allow-Origin "*" env=SIGN
Header set Access-Control-Allow-Headers "*" env=SIGN
but that did not work.
URLs might look like:
https://www.example.com/api/something/another/lastThis should set the headershttps://test.example.com/api/something/another/lastThis should set the headershttps://prod.example.com/api/something/another/lastThis should set the headershttps://www.example.com/hello/world/testThis should not.
已采纳解答
原帖链接 · MrWhite · CC BY-SA 4.0
the example URLs do not point to actual directories.
In that case the request is probably being rewritten to a front-controller that routes the API call?
When the rewriting process "loops" after the first rewrite (in a directory / .htaccess context), any environment variables that are set during the initial phase are prefixed with REDIRECT_. So, as in your example, SIGN is renamed REDIRECT_SIGN. So, it's probably this environment variable that needs to be checked, not SIGN.
For example:
SetEnvIf Request_URI "^/api" SIGN
Header set Access-Control-Allow-Origin "*" env=REDIRECT_SIGN
Header set Access-Control-Allow-Headers "*" env=REDIRECT_SIGN
For requests that start /api.
This may seem counter intuitive, but in a directory context the SIGN env var is set on the first phase of processing and the Header directive is processed late on the 2nd (or 3rd...) phase of processing.
If there are additional rewrite loops (unlikely) then this env var is further renamed to REDIRECT_REDIRECT_SIGN and so on.
This is not an issue if the directives are directly in the main server config or virtual host.
RewriteCond %{REQUEST_URI} api ENV=SIGN2
Incidentally, this is wholly invalid and would break your server. You set environment variables using the RewriteRule directive as @EOhm has pointed out.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
