提交工单

Ubuntu安装Apache并配置虚拟主机与PHP

安装

apt update
apt install apache2 -y
systemctl enable --now apache2
ufw allow 80/tcp && ufw allow 443/tcp

浏览器访问服务器 IP,看到 Apache 默认页即成功。

注意:Apache 和 Nginx 默认都监听 80 端口,同一台服务器上不要同时用默认配置运行两者。

目录结构

路径 作用
/etc/apache2/sites-available/ 站点配置
/etc/apache2/sites-enabled/ 已启用的站点
/etc/apache2/mods-enabled/ 已启用的模块
/var/log/apache2/ 日志

配置虚拟主机

nano /etc/apache2/sites-available/example.com.conf
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com

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

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

AllowOverride All 允许使用 .htaccess。

a2ensite example.com.conf
a2enmod rewrite
apache2ctl configtest
systemctl reload apache2

搭配 PHP-FPM

apt install php-fpm -y
a2enmod proxy_fcgi setenvif
a2enconf php8.3-fpm        # 版本号按实际安装的为准
systemctl reload apache2

HTTPS

apt install certbot python3-certbot-apache -y
certbot --apache -d example.com -d www.example.com

Apache 还是 Nginx

Apache Nginx
.htaccess 支持 不支持,规则写在站点配置中
静态文件、高并发 一般 资源占用更低
反向代理 可以 更常用
  • 程序依赖 .htaccess、或者从虚拟主机迁移过来:Apache 更省事
  • 新项目、反向代理 Node/Python/Docker:推荐 Nginx,见 Ubuntu 安装 Nginx