1

I'm just trying to set a header if the loaded page is home (/), however, I can't manage to do that. What I've tried:

#let's find var value - its echo / on the header
PassEnv REQUEST_URI
Header always set Echo %{REQUEST_URI}e

<If "%{REQUEST_URI} =~ m#^/$#">
   #some other rules - never hits
   Header always set Test "It works"
</If>

Could someone help?

MrWhite
  • 12,647
  • 4
  • 29
  • 41
Uly
  • 13
  • 4

1 Answers1

1

This is most probably the result of a conflict with mod_dir and the DirectoryIndex. (Or a standard internal rewrite, if you are using a front-controller pattern - although that wouldn't normally apply in this instance.)

<If> expressions are merged late, after mod_dir has already rewritten the request (in the form of an internal subrequest) to the directory index document, eg. /index.html. The REQUEST_URI server variable is updated to reflect the rewritten URL-path.

So, you either need to check for the directory index document:

<If "%{REQUEST_URI} =~ m#^/index\.html$#">
   #some other rules...
   Header always set Test "It works"
</If>

OR, check against THE_REQUEST server variable instead, which contains the first line of the request headers and does not change when the request is internally rewritten.

THE_REQUEST will contain a string of the form GET / HTTP/1.1 when the homepage (/) is requested.

For example:

<If "%{THE_REQUEST} =~ m#^[A-Z]{3,7}\s/\s#">
   #some other rules...
   Header always set Test "It works"
</If>

Aside:

PassEnv REQUEST_URI

The PassEnv directive is not required here. REQUEST_URI is already an Apache server variable and available to your script.

MrWhite
  • 12,647
  • 4
  • 29
  • 41
  • 1
    MrWhite many thanks for your help, the second option using the `THE_REQUEST` var worked perfect :) The problem with the first option is that I have a single entry point of index.php in my app, so `m#^/index\.php$#` is always true in any of the routes. Again, many thanks for your amazing answer and help ;) – Uly Mar 29 '21 at 19:44