2

I'm defining a RewriteMap in my Apache httpd configuration. (This is working correctly.)

RewriteMap redirects-list txt:/path/to/redirects.txt

But when the map file (/path/to/redirects.txt) doesn't exist, the server throws an error:

RewriteMap: file for map redirects-list not found:/path/to/redirects.txt

I want to make this fault-tolerant, where the RewriteMap is set if and only if the file exists.

(For example, if it doesn't exist, maybe there's a way to automatically use a fallback, a blank file like /dev/null.)

I'd appreciate any help.

MrWhite
  • 13,315
Anirvan
  • 401

2 Answers2

2

Use a real empty file or a file with comments. Changes to the file will be recognized by Apache without the need to reload/restart.

https://httpd.apache.org/docs/2.4/rewrite/rewritemap.html#txt

Cached lookups

The looked-up keys are cached by httpd until the mtime (modified time) of the mapfile changes, or the httpd server is restarted. This ensures better performance on maps that are called by many requests.

A missing RewriteMap file is an error (apachectl configtest) and /dev/null as file works, but is bad style. In this case it might be better to comment those lines in your config.

Freddy
  • 2,099
2

There doesn't seem to be a way to set a RewriteMap conditionally. I tried setting the RewriteMap in an <If> directive using an Apache expression to check the existence of the file. For example:

<If "-f '/path/to/redirects.txt'">
    RewriteMap redirects-list txt:/path/to/redirects.txt
</If>

However, this is syntactically invalid and the server will fail to start with error:

RewriteMap not allowed here

As stated already, you should test the config before (re)starting the Apache server.


It's worth noting that if there are dependent directives that use this (non-existent) RewriteMap then these will simply fail silently. (Even with LogLevel rewrite:trace6 there doesn't appear to be anything meaningful logged in this regard?). So, having the server fail to start when the map file does not exist would seem to be the better option (even though removing the map file later does not result in an "error").

MrWhite
  • 13,315