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

How do I use a custom variable in an If-Else statement inside an Apache config?

· 52CE 我爱测

Here's my code (I've commented out the if-else part as it's not working) snippets/contents of my config files /etc/httpd/conf.d/staff.vhost Define host_domain "staff" Include /etc/httpd/conf.d/stage_template.vhost /etc/httpd/conf…

问题原文

原帖链接 · mrjayviper · CC BY-SA 4.0

Here's my code (I've commented out the if-else part as it's not working)

snippets/contents of my config files

/etc/httpd/conf.d/staff.vhost

Define host_domain "staff"

Include /etc/httpd/conf.d/stage_template.vhost

/etc/httpd/conf.d/stage_template.vhost

    #<If "${host_domain} == 'main'">
    #    ServerAlias stage.myhost.com
    #</If>
    #<Else>
        ServerAlias stage-${host_domain}.myhost.com
    #</Else>

${host_domain} can have 3 possible values: main or staff or customer

I have tried these comparisons

  • "${host_domain} == 'main'"

    AH00526: Syntax error on line 9 of /etc/httpd/conf.d/stage_template.vhost: Cannot parse condition clause: syntax error, unexpected T_OP_STR_EQ, expecting '('

  • "%{host_domain} == 'main'"

    AH00526: Syntax error on line 9 of /etc/httpd/conf.d/stage_template.vhost: Cannot parse condition clause: Parse error near '%'

  • "'${host_domain}' == 'main'"

    AH00526: Syntax error on line 10 of /etc/httpd/conf.d/available_vhosts/stage_template.vhost: ServerAlias not allowed here

I was using this page as guide. But it's doesn't have any examples when using custom variables.

Thanks!

已采纳解答

原帖链接 · Esa Jokinen · CC BY-SA 4.0

Apache's If-Else statements are evaluated at request time, while Virtual Host Matching has its own logic. That's why it's likely that If-Else wouldn't work with ServerAlias at all, or it would give unexpected results. On the other hand, you state that your "${host_domain} can have 3 possible values". What you are trying to do is overly complicated, and you have several better approaches.

  • Use separate <VirtualHost> for each main, staff and customer.
  • Add all these virtualhost to a single <VirtualHost> with every option matching a single ServerAlias. Then, you can use If-Else statements inside the <VirtualHost> to alter specific configuration based on the %{HTTP_HOST} variable.
  • If there was several similar <VirtualHost>s (way more than just three) with just a certain changing parts in the configuration, Apache Module mod_macro would have been your choice. As the macros are evaluated when the server starts, building a static configuration out of them, it's more efficient than comparing the variables at request time.

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

资料来源与适用范围

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

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

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