www和非www VirtualHost的单行配置

时间:2018-02-13 11:06:29

标签: apache apache2 virtualhost apache2.4

我有很多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

2 个答案:

答案 0 :(得分:4)

不,这是不可能的。

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

您可以在ServerName中使用通配符,并在其上指定多个名称:

ServerAlias

ServerAlias *.example.com

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

答案 1 :(得分:0)

我喜欢的技巧是

<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

应该做的伎俩