完善Ubuntu上Apache配置的全流程指南
安装Apache2
更新软件包索引并安装Apache2,启动服务并设置开机自启:
sudo apt update && sudo apt install apache2
sudo systemctl start apache2
sudo systemctl enable apache2
验证安装
在浏览器访问服务器IP,若看到Apache默认欢迎页面,说明安装成功。
/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/public_html
<Directory /var/www/example.com/public_html>
Options Indexes FollowSymLinks
AllowOverride All # 允许.htaccess覆盖配置
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>
a2ensite命令启用配置,并重载Apache:sudo a2ensite example.com.conf
sudo systemctl reload apache2
sudo a2dissite 000-default.conf
sudo systemctl reload apache2
sudo a2enmod rewrite # URL重写(支持.htaccess)
sudo a2enmod ssl # SSL加密
sudo a2enmod deflate # 压缩(减少传输体积)
sudo a2enmod expires # 缓存控制(提升静态资源加载速度)
sudo a2dismod autoindex # 禁用目录列表(避免敏感信息泄露)
sudo systemctl restart apache2
event适用于高并发),编辑对应配置文件(如/etc/apache2/mods-enabled/mpm_event.conf):<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150 # 最大并发请求数(根据内存调整)
MaxConnectionsPerChild 0 # 0表示无限制(避免频繁重启进程)
</IfModule>
/etc/apache2/apache2.conf中添加:# 压缩HTML/CSS/JS等文本资源
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript
# 静态资源缓存(1天)
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 day"
ExpiresByType image/png "access plus 1 day"
ExpiresByType text/css "access plus 1 day"
</IfModule>
<Directory>配置中Options不包含Indexes,或添加-Indexes:<Directory /var/www/example.com/public_html>
Options -Indexes FollowSymLinks # 禁止目录列表
Require all granted
</Directory>
Require指令替代旧版Allow from,例如仅允许可信IP访问管理目录:<Directory /var/www/admin>
Require ip 192.168.1.100 # 替换为你的IP
</Directory>
sudo apt install certbot python3-certbot-apache
sudo certbot --apache -d example.com -d www.example.com # 自动配置SSL虚拟主机
000-default.conf,添加以下内容到<VirtualHost *:80>:RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
/etc/apache2/apache2.conf中修改日志格式,增加有用信息(如请求时间、客户端IP):LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
mod_status,默认启用),编辑/etc/apache2/mods-enabled/status.conf:<Location "/server-status">
SetHandler server-status
Require ip 127.0.0.1 # 仅本地访问(生产环境可限制为可信IP)
</Location>
重启Apache后,访问http://服务器IP/server-status查看实时状态。测试配置语法:修改配置文件后,使用以下命令检查语法错误:
sudo apachectl configtest
若输出Syntax OK,则配置正确。
重载Apache:修改配置后,无需重启即可应用更改:
sudo systemctl reload apache2
监控性能:使用top、htop或apachetop工具监控CPU、内存占用,根据实际情况调整MPM参数。
通过以上步骤,可完善Ubuntu上Apache的配置,实现多站点支持、性能优化、安全加固及便捷维护。