大网数据广告活动
服务器运维问答

Setup headers in apache2 if URL contains term

· 52CE 我爱测

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-O…

问题原文

原帖链接 · 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/last This should set the headers

  • https://test.example.com/api/something/another/last This should set the headers

  • https://prod.example.com/api/something/another/last This should set the headers

  • https://www.example.com/hello/world/test This 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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-10-27)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。