如何在Ubuntu中配置Apache虚拟主机

354
2025/4/8 3:32:56
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu中配置Apache虚拟主机可以让你在同一台服务器上托管多个网站。以下是详细的步骤:

1. 安装Apache

首先,确保你已经安装了Apache。如果没有安装,可以使用以下命令进行安装:

sudo apt update
sudo apt install apache2

2. 启用必要的模块

确保启用了mod_rewritemod_ssl模块(如果你打算使用SSL):

sudo a2enmod rewrite
sudo a2enmod ssl

3. 创建虚拟主机配置文件

每个虚拟主机都需要一个单独的配置文件。你可以在/etc/apache2/sites-available/目录下创建这些文件。

示例:创建第一个虚拟主机

sudo nano /etc/apache2/sites-available/example.com.conf

在文件中添加以下内容:

<VirtualHost *:80>
    ServerAdmin webmaster@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com

    <Directory /var/www/example.com>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

创建第二个虚拟主机

sudo nano /etc/apache2/sites-available/anotherdomain.com.conf

在文件中添加以下内容:

<VirtualHost *:80>
    ServerAdmin webmaster@anotherdomain.com
    ServerName anotherdomain.com
    ServerAlias www.anotherdomain.com
    DocumentRoot /var/www/anotherdomain.com

    <Directory /var/www/anotherdomain.com>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

4. 启用虚拟主机

使用a2ensite命令启用每个虚拟主机配置文件:

sudo a2ensite example.com.conf
sudo a2ensite anotherdomain.com.conf

5. 禁用默认站点(可选)

如果你不再需要默认的Apache站点,可以禁用它:

sudo a2dissite 000-default.conf

6. 重启Apache

每次更改配置后,都需要重启Apache以使更改生效:

sudo systemctl restart apache2

7. 配置DNS

确保你的域名解析正确指向你的服务器IP地址。你可以在你的DNS提供商的管理界面中添加A记录。

8. 测试配置

打开浏览器并访问你的域名,确保它们正确显示。

9. 使用SSL(可选)

如果你打算使用SSL,可以使用Let’s Encrypt免费获取SSL证书,并配置Apache以使用这些证书。

安装Certbot

sudo apt install certbot python3-certbot-apache

获取并安装SSL证书

sudo certbot --apache -d example.com -d www.example.com
sudo certbot --apache -d anotherdomain.com -d www.anotherdomain.com

按照提示完成证书的安装和配置。

通过以上步骤,你应该能够在Ubuntu上成功配置Apache虚拟主机。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: ubuntu怎么切换图形界面