要配置 Apache 服务器通过域名访问,需完成域名解析、虚拟主机配置及服务重启等步骤,以下是具体操作流程及注意事项,确保环境为已安装 Apache 的 Linux 系统(如 Ubuntu/CentOS)。

准备工作:域名解析与服务器环境
域名解析配置
登录域名管理后台(如阿里云、腾讯云),将域名解析到服务器的公网 IP,添加A记录:- 主机记录:
www(或 表示根域名) - 记录值:服务器公网 IP(如
0.113.10)
解析生效时间通常为几分钟至几小时,可通过ping 域名验证是否指向正确 IP。
- 主机记录:
确认 Apache 安装状态
Ubuntu/Debian 系统通过sudo apt install apache2安装,CentOS/RHEL 系统使用sudo yum install httpd,安装后检查服务状态:sudo systemctl status apache2 # Ubuntu sudo systemctl status httpd # CentOS
若未运行,执行
sudo systemctl start apache2启动。
配置虚拟主机
Apache 通过虚拟主机实现多域名访问,需创建配置文件并定义网站目录、权限等。
创建网站目录
在服务器上为域名创建网站根目录,并设置权限:
sudo mkdir -p /var/www/example.com/html sudo chown -R $USER:$USER /var/www/example.com/html # 将所有者设为当前用户 sudo chmod -R 755 /var/www/example.com/html # 设置读写权限
在目录中创建测试文件 index.html:

<!DOCTYPE html> <html> <head><title>Example Domain</title></head> <body><h1>Welcome to example.com!</h1></body> </html>
创建虚拟主机配置文件
Ubuntu/Debian:
在/etc/apache2/sites-available/目录下创建新文件example.com.conf:<VirtualHost *:80> ServerName example.com # 主域名 ServerAlias www.example.com # 子域名(可选) DocumentRoot /var/www/example.com/html # 网站根目录 ErrorLog ${APACHE_LOG_DIR}/error.log # 错误日志 CustomLog ${APACHE_LOG_DIR}/access.log combined # 访问日志 </VirtualHost>CentOS/RHEL:
在/etc/httpd/conf.d/目录下创建example.com.conf同上(注意路径变量差异,如日志路径为/var/log/httpd/)。
启用虚拟主机并测试配置
- Ubuntu:启用站点并启用
rewrite模块(用于后续 HTTPS 重定向等):sudo a2ensite example.com.conf sudo a2enmod rewrite
- CentOS:直接创建文件即可,无需额外启用。
测试配置语法是否正确:
sudo apache2ctl configtest # Ubuntu sudo httpd -t # CentOS
若无报错(显示 Syntax OK),则继续下一步。
重启 Apache 服务
保存配置后,重启 Apache 使配置生效:
sudo systemctl restart apache2 # Ubuntu sudo systemctl restart httpd # CentOS
在浏览器访问 http://example.com 或 http://www.example.com,应显示 index.html
配置 HTTPS(可选但推荐)
为提升安全性,可申请免费 SSL 证书(如 Let's Encrypt)并启用 HTTPS。

安装 Certbot:
sudo apt install certbot python3-certbot-apache # Ubuntu sudo yum install certbot python3-certbot-apache # CentOS
获取证书并配置 HTTPS:
sudo certbot --apache -d example.com -d www.example.com
Certbot 会自动修改虚拟主机配置,添加 443 端口(HTTPS)配置,并强制 HTTP 重定向到 HTTPS。
验证自动续签:
Certbot 默认设置自动续签,可通过sudo certbot renew --dry-run测试。
常见问题排查
| 问题现象 | 可能原因及解决方案 |
|---|---|
| 访问域名显示 403 Forbidden | 检查网站目录权限(755)、文件所有者是否为当前用户,或 DocumentRoot 路径是否正确。 |
| 访问域名显示 404 Not Found | 确认 DocumentRoot 下的 index.html 是否存在,或检查 DirectoryIndex 配置。 |
| 多域名冲突 | 确保每个虚拟主机的 ServerName 唯一,避免重复。 |
| HTTPS 证书无效 | 检查证书过期时间(sudo certbot certificates),确认防火墙是否放行 443 端口。 |
通过以上步骤,即可完成 Apache 服务器的域名访问配置,建议定期备份配置文件(如 /etc/apache2/sites-available/ 或 /etc/httpd/conf.d/),并在修改后测试语法,确保服务稳定运行。
图片来源于AI模型,如侵权请联系管理员。作者:酷小编,如若转载,请注明出处:https://www.kufanyun.com/ask/31708.html
