温馨提示×

centos apache2怎样开伪静态

小樊
39
2026-10-17 14:35:35
栏目: 智能运维

在 CentOS 下,如果你说的是 Apache(httpd) 开启伪静态(Rewrite),常见做法如下(以 CentOS 7/8 + Apache 2.4 为例):


一、确认 Apache 已安装

httpd -v
# 或
apachectl -v

如果没装:

yum install httpd -y
# CentOS 8 用
dnf install httpd -y

二、开启 mod_rewrite 模块

CentOS 默认 Apache 一般已加载 mod_rewrite,可确认:

httpd -M | grep rewrite

如果有 rewrite_module,说明已开启。

如未开启(很少见):

vi /etc/httpd/conf/httpd.conf

找到并取消注释:

LoadModule rewrite_module modules/mod_rewrite.so

三、修改 Apache 配置允许 .htaccess

编辑虚拟主机或主配置:

vi /etc/httpd/conf/httpd.conf

或你的站点配置(如 /etc/httpd/conf.d/xxx.conf)

确保有:

<Directory "/var/www/html">
    AllowOverride All
</Directory>

⚠️ AllowOverride None 会导致伪静态失效


四、重启 Apache

systemctl restart httpd

五、写 .htaccess 规则(示例)

在网站根目录(如 /var/www/html)创建:

vi /var/www/html/.htaccess

示例 1:基础伪静态

RewriteEngine On
RewriteRule ^article/([0-9]+)\.html$ article.php?id=$1 [L]

示例 2:ThinkPHP

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]

示例 3:WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

六、常见问题排查

  1. 伪静态无效
    • 检查 AllowOverride All
    • 检查 .htaccess 是否在正确目录
  2. 403 错误
    chmod 644 .htaccess
    
  3. SELinux 导致失败
    setsebool -P httpd_can_network_connect 1
    

七、Apache2 说明(重要)

CentOS 默认是 httpd,不是 apache2
apache2 是 Ubuntu/Debian 的叫法


如果你用的是 某种框架(WordPress / ThinkPHP / Laravel) 或 面板(宝塔 / cPanel),可以告诉我,我可以给你更精确的配置。

0 踩