温馨提示×

linux apache怎么配置

小樊
50
2026-10-29 00:42:11
栏目: 智能运维

下面给你一份Linux 下 Apache(httpd)常见配置指南,适用于 CentOS / Rocky / Alma(yum/dnf) 和 Ubuntu / Debian(apt)。


一、安装 Apache

CentOS / Rocky / Alma

sudo dnf install httpd -y
sudo systemctl start httpd
sudo systemctl enable httpd

Ubuntu / Debian

sudo apt update
sudo apt install apache2 -y
sudo systemctl start apache2
sudo systemctl enable apache2

二、目录结构说明

CentOS

  • 主配置文件:/etc/httpd/conf/httpd.conf
  • 虚拟主机:/etc/httpd/conf.d/
  • 网站根目录:/var/www/html

Ubuntu

  • 主配置文件:/etc/apache2/apache2.conf
  • 虚拟主机:/etc/apache2/sites-available/
  • 启用配置:/etc/apache2/sites-enabled/
  • 网站根目录:/var/www/html

三、基础配置(修改端口 / 根目录)

修改监听端口(httpd.conf)

Listen 80
# Listen 8080

修改网站根目录

DocumentRoot "/var/www/html"
<Directory "/var/www/html">
    AllowOverride All
    Require all granted
</Directory>

修改后重启:

# CentOS
systemctl restart httpd

# Ubuntu
systemctl restart apache2

四、配置虚拟主机(多网站)

CentOS

新建文件:

vim /etc/httpd/conf.d/example.conf
<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot /var/www/example
    <Directory /var/www/example>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Ubuntu

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

启用站点:

a2ensite example.conf
systemctl reload apache2

五、开启 URL 重写(伪静态)

Ubuntu

a2enmod rewrite
systemctl restart apache2

CentOS

vim /etc/httpd/conf/httpd.conf

确保:

LoadModule rewrite_module modules/mod_rewrite.so

.htaccess 示例:

RewriteEngine On
RewriteRule ^page/([0-9]+)$ index.php?id=$1

六、配置 HTTPS(SSL)

安装模块

# CentOS
yum install mod_ssl

# Ubuntu
a2enmod ssl

示例 SSL 虚拟主机

<VirtualHost *:443>
    ServerName www.example.com
    DocumentRoot /var/www/example
    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/example.crt
    SSLCertificateKeyFile /etc/ssl/private/example.key
</VirtualHost>

七、防火墙放行

# firewalld
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

# ufw
ufw allow 80
ufw allow 443

八、常见问题排查

# 查看错误日志
tail -f /var/log/httpd/error_log     # CentOS
tail -f /var/log/apache2/error.log   # Ubuntu

# 配置语法检查
apachectl configtest

如果你有具体需求(比如:PHP 环境、反向代理、多域名、LNMP 对比、Docker 里跑 Apache),可以直接告诉我,我可以给你针对性配置示例。

0 踩