一台 apache 服务器托管多个网站的方法

From 清冽之泉
Revision as of 16:15, 19 October 2024 by Mwroot (talk | contribs)
Jump to navigation Jump to search

一台服务器放多个网站,无外乎子目录、子域名两种方法。

子目录

<VirtualHost *:80>
    ServerName sample.com
    DocumentRoot /var/www/site1
    <Directory /var/www/site1>
        AllowOverride All
        Require all granted
    </Directory>

    Alias /site2 /var/www/site2
    <Directory /var/www/site2>
        AllowOverride All
        Require all granted
    </Directory>

    Alias /site3 /var/www/site3
    <Directory /var/www/site3>
        AllowOverride All
        Require all granted
    </Directory>

    Alias /site4 /var/www/site4
    <Directory /var/www/site4>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

# 这种方法的要点在于厘清三个没人说但很符合直觉的共识:
# 如果有多个 xxx.conf,则 apache 会按照首字母排序读取第一个配置
# 如果想一个域名的子目录下托管多个网站,实现的方式则是第一个默认读取,后续的通过 Alias /subdirectory 读取
# DocumentRoot 是 index.html 或 index.php 的目录

子域名

<VirtualHost *:80>
    ServerName site1.sample.com
    DocumentRoot /var/www/site1
    <Directory /var/www/site1>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName site2.sample.com
    DocumentRoot /var/www/site2
    <Directory /var/www/site2>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName site3.sample.com
    DocumentRoot /var/www/site3
    <Directory /var/www/site3>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName site4.sample.com
    DocumentRoot /var/www/site4
    <Directory /var/www/site4>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

# 子域名的多网站托管方式,很符合单网站托管方式操作方法。只需注意一点即可:
# ServerName 是你注册的域名 yourdomain.com,ServerAlias 可以是 www.yourdomain.com

最后,不论子目录托管多站,还是子域名托管多站,所牵涉的目录都要在 Directory 里设定权限,有时还涉及 FollowSymLinks 让服务器有权限读取符号链接。

鸣谢:本文全部核心来自于 chatgpt,感谢这个最好的老师。