我在阿里云服务器上,安装了Ubuntu实例,并使用Apache部署了一个网站。
除了一个博客网站外,我还有一个平时高频使用的自己设计的导航页,也放在了这个网站根目录中。
手里有两个域名,就想一个域名指向博客首页,一个域名就直接指向这个导航页。
于是,就行动起来,一顿操作,通过配置虚拟主机(Virtual Hosts)实现不同域名指向同一服务器上不同的页面。以下是具体实现方法:
实现原理
Apache 的虚拟主机功能允许你基于不同的域名(或 IP 地址、端口)配置不同的网站内容。即使多个域名指向同一服务器 IP,也可以通过虚拟主机配置让它们访问不同的页面。
具体步骤
- 确保 Apache 已安装并运行
sudo apt update
sudo apt install apache2
- 创建网站目录结构 假设你的网站根目录是
/var/www/mywebsite,其中包含index.html和index.php:
sudo mkdir -p /var/www/mywebsite
# 放入你的 index.html 和 index.php 文件
- 配置虚拟主机 在
/etc/apache2/sites-available/目录下创建两个配置文件: - 为域名 A 创建配置文件
domainA.conf:
<VirtualHost *:80>
ServerName domainA.com
ServerAlias www.domainA.com
DocumentRoot /var/www/mywebsite
DirectoryIndex index.html # 优先加载 index.html
<Directory /var/www/mywebsite>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/domainA_error.log
CustomLog ${APACHE_LOG_DIR}/domainA_access.log combined
</VirtualHost>
- 为域名 B 创建配置文件
domainB.conf:
<VirtualHost *:80>
ServerName domainB.com
ServerAlias www.domainB.com
DocumentRoot /var/www/mywebsite
DirectoryIndex index.php # 优先加载 index.php
<Directory /var/www/mywebsite>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/domainB_error.log
CustomLog ${APACHE_LOG_DIR}/domainB_access.log combined
</VirtualHost>
- 启用虚拟主机配置
sudo a2ensite domainA.conf
sudo a2ensite domainB.conf
- 禁用默认配置(可选)
sudo a2dissite 000-default.conf
- 重启 Apache 服务
sudo systemctl restart apache2
- 关键配置说明
ServerName:指定域名DocumentRoot:设置网站根目录(两个域名可设为相同)DirectoryIndex:指定默认加载的首页文件,这里分别设置为index.html和index.php
这样配置后,访问 domainA.com 会默认加载 index.html,而访问 domainB.com 会默认加载 index.php,实现了不同域名指向同一目录下不同页面的需求。
如果需要配置 HTTPS(SSL/TLS),还需要为每个域名配置 SSL 证书并添加 443 端口的虚拟主机配置(我没有)。
阅读量:
331