【问题标题】:One-line configuration for both www and non-www VirtualHostwww 和非 www VirtualHost 的单行配置
【发布时间】:2018-07-23 17:41:23
【问题描述】:

我有很多VirtualHost,看来我们每次都需要做这两行:

<VirtualHost *:80>
  ...
  ServerName www.example.com
  ServerAlias example.com

是否有允许执行此操作的单线解决方案?

<VirtualHost *:80>
  ServerName *.example.com   # works for both http://example.com and http://www.example.com

即无需复制example.com

【问题讨论】:

  • 没有。你为什么要这样做?你按角色付费? :-)
  • @Nic3500 我在5 1/4" 上进行所有服务器配置备份。
  • 那就考虑使用gzip/bzip2/xz/etc... ;-)
  • 我不确定我是否完全理解了您的问题,但根据httpd.apache.org/docs/2.4/vhosts/name-based.html ServerAlias example.com *.example.com 那么对example.com 域中所有主机的请求将由www.example.com 虚拟主机提供服务.通配符 * 和 ?可用于匹配名称。当然,不能随便编个名字放在ServerName 或ServerAlias 中。您必须首先正确配置 DNS 服务器,以将这些名称映射到与您的服务器关联的 IP 地址。
  • 另请参阅:httpd.apache.org/docs/2.4/vhosts/examples.html 使用 _default_ 虚拟主机

标签: apache apache2 virtualhost apache2.4


【解决方案1】:

不,这是不可能的。

ServerName用于唯一标识主机的协议、名称和端口。它只接受一个参数,不接受通配符。

ServerAlias中可以使用通配符,也可以在上面指定多个名称:

ServerAlias *.example.com

ServerAlias www1.example.com www2.example.com www3 foo

来源:https://httpd.apache.org/docs/2.4/mod/core.html#serveralias

【讨论】:

  • 那么我可以只使用 ServerAlias *.example.com 而不使用ServerName 吗?
  • 不幸的是,IIRC 每个虚拟主机都必须有一个ServerName
【解决方案2】:

我喜欢做的一个技巧是

<VirtualHost *:80>
    Include                 /.../example.com.conf.include
</VirtualHost>
<VirtualHost *:443>
    Include                 /.../example.com.conf.include
    SSLCertificateFile      /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile   /etc/letsencrypt/live/example.com/privkey.pem
    Include                 /etc/letsencrypt/options-ssl-apache.conf #optional, maybe you should not do that
</VirtualHost>

还有 xxx.conf.include 文件,如:

ServerAdmin someone@somewhere.tld
ServerName example.com
ServerAlias example.com *.example.com andmore.example.com
DocumentRoot /var/www/html/example.com
ErrorLog /.../example.com_error.log
CustomLog /.../example.com_custom.log combined

<Directory /var/www/html/example.com>
    Options Indexes FollowSymLinks
    AllowOverride AuthConfig
    Order allow,deny
    allow from all
</Directory>

这样,您可以在完全相同的配置文件中拥有 HTTP 和 HTTPS 虚拟主机。

具体到你的问题,

ServerAlias *.example.com

应该做的伎俩

【讨论】:

  • 特别是你的问题ServerAlias *.example.com 应该可以解决问题:我们仍然需要添加另一个ServerName,对吧?
  • 哦啊……对不起……是的,你仍然需要ServerName。我想建议您检查是否有任何方法可以将变量包含到配置中,但是由于我对此了解不多,所以我没有建议。我上面的解决方案只是节省了更多的写作和双重编辑,所以我想也许你更喜欢这样,而不是节省一行。
猜你喜欢
  • 2018-01-07
  • 2018-11-15
  • 2017-11-23
  • 2011-12-18
  • 2011-05-01
  • 2017-12-04
  • 2019-01-28
  • 2014-12-16
  • 2013-10-16
相关资源
最近更新 更多