Section: User Contributed Perl Documentation (3)
Updated: 2003-11-04


Config::ApacheFormat - use Apache format config files 


Config files used with this module are in Apache's format:

  # comment here  RootDir /path/foo  LogDir  /path/foo/log  Colors red green orange blue \         black teal  <Directory /path/foo>     # override Colors inside block     Colors red blue black  </Directory>

Code to use this config file might look like:

  use Config::ApacheFormat;  # load a conf file  my $config = Config::ApacheFormat->new();  $config->read("my.conf");  # access some parameters  $root_dir = $config->get("RootDir");  $log_dir  = $config->get("LogDir");  @colors   = $config->get("colors");  # using the autoloaded methods  $config->autoload_support(1);  $root_dir = $config->RootDir;  $log_dir  = $config->logdir;  # access parameters inside a block  my $block = $config->block(Directory => "/path/foo");  @colors = $block->get("colors");  $root_dir = $block->get("root_dir");


This module is designed to parse a configuration file in the samesyntax used by the Apache web server (see fordetails). This allows you to build applications which can be easilymanaged by experienced Apache admins. Also, by using this module,you'll benefit from the support for nested blocks with built-inparameter inheritance. This can greatly reduce the amount or repeatedinformation in your configuration files.

A good reference to the Apache configuration file format can be foundhere:

To quote from that document, concerning directive syntax:

 Apache configuration files contain one directive per line. The back-slash "\" may be used as the last character on a line to indicate that the directive continues onto the next line. There must be no other characters or white space between the back-slash and the end of the line. Directives in the configuration files are case-insensitive, but arguments to directives are often case sensitive. Lines that begin with the hash character "#" are considered comments, and are ignored. Comments may not be included on a line after a configuration directive. Blank lines and white space occurring before a directive are ignored, so you may indent directives for clarity.

And block notation:

 Directives placed in the main configuration files apply to the entire server. If you wish to change the configuration for only a part of the server, you can scope your directives by placing them in <Directory>, <DirectoryMatch>, <Files>, <FilesMatch>, <Location>, and <LocationMatch> sections. These sections limit the application of the directives which they enclose to particular filesystem locations or URLs. They can also be nested, allowing for very fine grained configuration.

This module will parse actual Apache configuration files, but you will need to set some options to non-default values. See ``Parsing a Real Apache Config File''. 


$config = Config::ApacheFormat->new(opt => value)
This method creates an object that can then be used to read configurationfiles. It does not actually read any files; for that, use the "read()"method below. The object supports the following attributes, all of whichmay be set through "new()":
Set this to 0 to turn off the inheritance feature. Block inheritancemeans that variables declared outside a block are available frominside the block unless overriden. Defaults to 1.
When this is set to 1, the directive ``Include'' will be treatedspecially by the parser. It will cause the value to be treated as afilename and that filename will be read in. If you use ``Include''with a directory, every file in that directory will be included.This matches Apache's behavior and allows users to break up configuration files into multiple, possibly shared, pieces. Defaults to 1.
Set this to 1 and all your directives will be available as objectmethods. So instead of:


You can write:


Defaults to 0.

Set this to 1 to preserve the case of directive names. Otherwise, allnames will be "lc()"ed and matched case-insensitively. Defaults to 0.
If set to 1, then during parsing, the strings ``Yes'', ``On'', and ``True''will be converted to 1, and the strings ``No'', ``Off'', and ``False'' willbe converted to 0. This allows you to more easily use "get()" in conditional statements.

For example:

  # httpd.conf  UseCanonicalName  On

Then in Perl:

  $config = Config::ApacheFormat->new(fix_booleans => 1);  $config->read("httpd.conf");  if ($config->get("UseCanonicalName")) {      # this will get executed if set to Yes/On/True  }

This option defaults to 0.

If set, then you can use variable expansion in your config file by prefixing directives with a "$". Hopefully this seems logical to you:

  Website     http://my.own.dom  JScript     $Website/js  Images      $Website/images

Undefined variables in your config file will result in an error. Touse a literal "$", simply prefix it with a "\" (backslash). Likein Perl, you can use brackets to delimit the variables more precisely:

  Nickname    Rob  Fullname    ${Nickname}ert

Since only scalars are supported, if you use a multi-value, you willonly get back the first one:

  Options     Plus Minus "About the Same"  Values      $Options

In this examples, ``Values'' will become ``Plus''. This is seldom a limitationsince in most cases, variable subsitution is used like the first exampleshows. This option defaults to 0.

If this is set to 1, then the special "SetEnv" directive will be setvalues in the environment via %ENV. Also, the special "UnSetEnv"directive will delete environment variables.

For example:

  # $ENV{PATH} = "/usr/sbin:/usr/bin"  SetEnv PATH "/usr/sbin:/usr/bin"  # $ENV{MY_SPECIAL_VAR} = 10  SetEnv MY_SPECIAL_VAR 10  # delete $ENV{THIS}  UnsetEnv THIS

This option defaults to 0.

If you provide an array of directive names then syntax errors will begenerated during parsing for invalid directives. Otherwise, anydirective name will be accepted. For exmaple, to only allowdirectives called ``Bar'' and ``Bif'':

  $config = Config::ApacheFormat->new(                      valid_directives => [qw(Bar Bif)],                                     );
If you provide an array of block names then syntax errors will begenerated during parsing for invalid blocks. Otherwise, any blockname will be accepted. For exmaple, to only allow ``Directory'' and``Location'' blocks in your config file:

  $config = Config::ApacheFormat->new(                      valid_blocks => [qw(Directory Location)],                                     );
This directive controls the name of the include directive. By defaultit is "['Include']", but you can set it to any list of directivenames.
This controls what the root directive is, if any. If you set this tothe name of a directive it will be used as a base directory for"Include" processing. This mimics the behavior of "ServerRoot" inreal Apache config files, and as such you'll want to set it to'ServerRoot' when parsing an Apache config. The default is "undef".
This determines which directives (if any) should be parsed so that thefirst value is actually a key into the remaining values. For example,"AddHandler" is such a directive.

  AddHandler cgi-script .cgi .sh  AddHandler server-parsed .shtml

To parse this correctly, use:

  $config = Config::ApacheFormat->new(                      hash_directives => [qw(AddHandler PerlSetVar)]                                     );

Then, use the two-argument form of "get()":

  @values = $config->get(AddHandler => 'cgi-script');

This allows you to access each directive individually, which is neededto correctly handle certain special-case Apache settings.

This option controls how duplicate directives are handled. By default,if multiple directives of the same name are encountered, the last onewins:

  Port 8080  # ...  Port 5053

In this case, the directive "Port" would be set to the last value, 5053.This is useful because it allows you to include other config files, whichyou can then override:

  # default setup  Include /my/app/defaults.conf  # override port  Port 5053

In addition to this default behavior, "Config::ApacheFormat" also supportsthe following modes:

  last     -  the value from the last one is kept (default)  error    -  duplicate directives result in an error  combine  -  combine values of duplicate directives together

These should be self-explanatory. If set to "error", any duplicateswill result in an error. If set to "last" (the default), the lastvalue wins. If set to "combine", then duplicate directives arecombined together, just like they had been specified on the same line.

All of the above attributes are also available as accessor methods. Thus,this:

  $config = Config::ApacheFormat->new(inheritance_support => 0,                                      include_support => 1);

Is equivalent to:

  $config = Config::ApacheFormat->new();  $config->inheritance_support(0);  $config->include_support(1);
Reads a configuration file into the config object. You must passeither the path of the file to be read or a reference to an openfilehandle. If an error is encountered while reading the file, thismethod will die().

Calling read() more than once will add the new configuration valuesfrom another source, overwriting any conflicting values. Call clear()first if you want to read a new set from scratch.

$value = $config->get(var_name)
@vals = $config->get(list_name)
$value = $config->get(hash_var_name, key)
Returns values from the configuration file. If the directive containsa single value, it will be returned. If the directive contains a listof values then they will be returned as a list. If the directive doesnot exist in the configuration file then nothing will be returned(undef in scalar context, empty list in list context).

For example, given this confiuration file:

  Foo 1  Bar bif baz bop

The following code would work as expected:

  my $foo = $config->get("Foo");   # $foo = 1  my @bar = $config->get("Bar");   # @bar = ("bif", "baz", "bop")

If the name is the name of a block tag in the configuration file thena list of available block specifiers will be returned. For example,given this configuration file:

  <Site big>     Size 10  </Site>  <Site small>     Size 1  </Site>

This call:

  @sites = $config->get("Site");

Will return "([ Site =" ``big''], [ Site => ``small'' ])>. These arrayscan then be used with the block() method described below.

If the directive was included in the file but did not have a value,1 is returned by get().

Calling get() with no arguments will return the names of all availabledirectives.

Directives declared in "hash_directives" require a key value:

  $handler = $config->get("AddHandler", "cgi-script");

"directive()" is available as an alias for "get()".

$block = $config->block(BlockName)
$block = $config->block(Directory => /foo/bar)
$block = $config->block(Directory => ~ => ^.*/bar)
This method returns a Config::ApacheFormat object used to access thevalues inside a block. Parameters specified within the block will beavailable. Also, if inheritance is turned on (the default), valuesset outside the block that are not overwritten inside the block willalso be available. For example, given this file:

  MaxSize 100  <Site "big">     Size 10  </Site>  <Site "small">     Size 1  </Site>

this code:

  print "Max: ", $config->get("MaxSize"), "\n";  $block = $config->block(Site => "big");  print "Big: ", $block->get("Size"), " / ",                  $block->get("MaxSize"), "\n";  $block = $config->block(Site => "small");  print "Small: ", $block->get("Size"), " / ",                    $block->get("MaxSize"), "\n";

will print:

  Max: 100  Big: 10 / 100  Small: 1 / 100

Note that "block()" does not require any particular number ofparameters. Any number will work, as long as they uniquely identify ablock in the configuration file. To get a list of available blocks,use get() with the name of the block tag.

This method will die() if no block can be found matching the specifierpassed in.

Clears out all data in $config. Call before re-calling$config->read() for a fresh read.
This returns a dumped copy of the current configuration. It can beused on a block object as well. Since it returns a string, you shouldsay:

    print $config->dump;


    for ($config->block(VirtualHost => '')) {        print $_->dump;    }

If you want to see any output.


Parsing a Real Apache Config File

To parse a real Apache config file (ex. "httpd.conf") you'll need touse some non-default options. Here's a reasonable starting point:

  $config = Config::ApacheFormat->new(              root_directive     => 'ServerRoot',              hash_directives    => [ 'AddHandler' ],              include_directives => [ 'Include',                                       'AccessConfig',                                       'ResourceConfig' ],              setenv_vars        => 1,              fix_booleans       => 1);


Some possible ideas for future development:
Add a set() method. (useless?)
Add a write() method to create a new configuration file. (useless?)


I know of no bugs in this software. If you find one, please create abug report at:

Include the version of the module you're using and a small piece ofcode that I can run which demonstrates the problem. 


Copyright (C) 2002-2003 Sam Tregar

This program is free software; you can redistribute it and/or modifyit under the same terms as Perl 5 itself. 


Sam Tregar <>
Original author and maintainer
Nathan Wiger <>
Porting of features from Apache::ConfigFile





Hey! The above document had some coding errors, which are explained below:
Around line 94:
'=item' outside of any '=over'
Around line 1017:
You forgot a '=back' before '=head1'
Around line 1068:
'=item' outside of any '=over'
Around line 1076:
You forgot a '=back' before '=head1'



Parsing a Real Apache Config File

This document was created byman2html,using the manual pages.