首先确保Ubuntu系统软件包是最新的,避免因旧版本导致兼容性问题:
sudo apt update && sudo apt upgrade -y
通过APT包管理器快速安装Apache2 Web服务器,安装完成后会自动启动服务:
sudo apt install apache2 -y
启动Apache服务并配置其在系统启动时自动运行,确保服务器重启后网站仍可访问:
sudo systemctl start apache2
sudo systemctl enable apache2
检查Apache服务是否处于“active (running)”状态,确认服务正常运行:
sudo systemctl status apache2
若系统启用了UFW防火墙,需允许HTTP(端口80)和HTTPS(端口443)流量,确保外部设备可访问网站:
sudo ufw allow 'Apache Full'
在/var/www/html/下创建专用目录存放网站文件(建议以域名命名,便于管理),并设置合理的目录结构:
sudo mkdir -p /var/www/yourwebsite.com/public_html
将网站目录的所有权赋予Apache运行的用户(www-data),并设置权限为755(所有者可读写执行,其他用户仅可读执行):
sudo chown -R www-data:www-data /var/www/yourwebsite.com
sudo chmod -R 755 /var/www/yourwebsite.com
在网站目录下创建index.html作为首页,写入简单的欢迎内容(可根据需求修改为动态页面):
sudo nano /var/www/yourwebsite.com/public_html/index.html
输入以下内容后保存退出(Ctrl+X → Y → Enter):
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Your Website</title>
</head>
<body>
<h1>Hello from Ubuntu + Apache!</h1>
<p>Your website is now live.</p>
</body>
</html>
若需托管多个网站或实现更灵活的管理,创建虚拟主机配置文件:
sudo nano /etc/apache2/sites-available/yourwebsite.com.conf
添加以下内容(替换yourwebsite.com为你的域名,/var/www/yourwebsite.com/public_html为网站目录):
<VirtualHost *:80>
ServerAdmin webmaster@yourwebsite.com
ServerName yourwebsite.com
ServerAlias www.yourwebsite.com
DocumentRoot /var/www/yourwebsite.com/public_html
<Directory /var/www/yourwebsite.com/public_html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/yourwebsite_error.log
CustomLog ${APACHE_LOG_DIR}/yourwebsite_access.log combined
</VirtualHost>
关键参数说明:
ServerName:主域名;ServerAlias:域名别名(如www前缀);DocumentRoot:网站文件根目录;<Directory>:目录权限设置,AllowOverride All允许.htaccess文件覆盖配置。启用新创建的虚拟主机配置,并禁用默认站点(避免冲突):
sudo a2ensite yourwebsite.com.conf
sudo a2dissite 000-default.conf # 可选:禁用默认站点
应用所有更改,重启Apache服务:
sudo systemctl reload apache2 # 或使用 sudo systemctl restart apache2
在浏览器中输入服务器IP地址或域名(如http://your_server_ip或http://yourwebsite.com),若看到“Hello from Ubuntu + Apache!”页面,说明部署成功。
为提升网站安全性,使用Let’s Encrypt免费获取SSL证书,实现HTTPS加密:
sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache -d yourwebsite.com -d www.yourwebsite.com
按照提示完成证书申请(需验证域名所有权),证书会自动配置到Apache中。此后访问https://yourwebsite.com将显示安全锁标志。
www-data用户可访问),确认<Directory>配置正确;sudo apachectl configtest检查配置,修复错误后重启Apache。