How to define a variable in the configuration of a Virtual Host, to avoid repetition?

2

I always get annoyed when I see that my virtualhost ends up being configured like this:

<VirtualHost :80>

    ServerName meusite.local
    ServerAlias www.meusite.local


    DocumentRoot /var/www/meusite/public

    ErrorLog /var/www/meusite/__apache__.log

</VirtualHost>

Note that I've repeated /var/www/meusite/ twice there, and considering that I might have more settings that would use that same root folder, it might be a pain to do that.

I was wondering if there is any way to save this /var/www/meusite to a variable and use it, concatenating with /public and __apache__.log , for example.

Is there any way to do this?

    
asked by anonymous 10.08.2018 / 22:45

2 answers

2

In Apache Core there is Define , as per the documentation: link

Used to define variables

Define root_dir /var/www/meusite

<VirtualHost :80>    
    ServerName meusite.local
    ServerAlias www.meusite.local

    DocumentRoot ${root_dir}/public

    ErrorLog ${root_dir}/__apache__.log
</VirtualHost>

On multiple hosts:

Define root_dir1 /var/www/meusite1
Define root_dir2 /var/www/meusite2

<VirtualHost meusite1.local:80>
    ServerAlias www.meusite2.local

    DocumentRoot ${root_dir1}/public

    ErrorLog ${root_dir1}/__apache__.log
</VirtualHost>

<VirtualHost meusite2.local:80>
    ServerAlias www.meusite2.local

    DocumentRoot ${root_dir2}/public

    ErrorLog ${root_dir2}/__apache__.log
</VirtualHost>

It's worth noting that if you use too many "includes" maybe one and a half may accidentally end up conflicting, and include something twice, in this case you can use <IfDefined> to check if a file or if a variable has already been set

<IfDefine !FOO>
Include Foo.config
</IfDefine>

In this example, of course, there should be something like% w /

Define FOO valor

In addition to defining it is possible to remove a variable, like this:

<IfDefine FOO>
UnDefine FOO
</IfDefine>

It's good to point out this piece of documentation:

  

Virtual Host scope and pitfalls

     

While this directive is supported in virtual host context, the changes   it is visible to any later configuration directives, beyond any   enclosing virtual host.

Translating:

  

The scope of Virtual Host and its traps

     

Although this policy is supported in the context of Virtual Host, the changes made are visible to any later configuration policy, in addition to any other Virtual Host included.

    
10.08.2018 / 23:03
2

You can use the Define directive

See document link

Define pasta /var/www/meusite/


<VirtualHost :80>

    ServerName meusite.local
    ServerAlias www.meusite.local


    DocumentRoot ${pasta}public

    ErrorLog ${pasta}__apache__.log

</VirtualHost>
    
10.08.2018 / 22:55