温馨提示×

centos apache怎么配置伪静态

小樊
42
2026-09-30 03:03:11
栏目: 智能运维

在 CentOS 上,使用 Apache 配置“伪静态”(URL Rewrite)通常是通过 mod_rewrite 模块实现的。下面按常见场景一步步说明。


一、确认 Apache 已安装并启用 mod_rewrite

1. 查看 Apache 是否安装

httpd -v
# 或
apachectl -v

2. 检查 mod_rewrite 是否启用

httpd -M | grep rewrite

如果有:

rewrite_module (shared)

说明已启用。

如果没有,编辑 Apache 配置:

vi /etc/httpd/conf/httpd.conf

找到并取消注释(删掉前面的 #):

LoadModule rewrite_module modules/mod_rewrite.so

二、允许目录使用 .htaccess(关键)

Apache 默认可能禁止 .htaccess 重写规则生效。

编辑虚拟主机或主配置:

vi /etc/httpd/conf/httpd.conf

或

vi /etc/httpd/conf.d/your-site.conf

示例:

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

⚠️ 如果是 CentOS 7+,默认是 Apache 2.4,用 Require all granted

重启 Apache:

systemctl restart httpd

三、使用 .htaccess 配置伪静态(最常用)

进入网站根目录:

cd /var/www/html
vi .htaccess

最基础示例(开启重写)

RewriteEngine On

示例 1:把 index.php?id=1 伪静态成 /article/1

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

访问:

http://域名/article/1

实际执行:

index.php?id=1

示例 2:ThinkPHP 伪静态

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

示例 3:WordPress 伪静态

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

四、在 Apache 配置中直接写(不推荐但可用)

也可以不写 .htaccess,直接写在 <VirtualHost> 中:

<VirtualHost *:80>
    DocumentRoot /var/www/html
    ServerName example.com

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

    RewriteEngine On
    RewriteRule ^article/([0-9]+)$ index.php?id=$1 [L]
</VirtualHost>

五、常见错误排查

1. 伪静态不生效

  • .htaccess 是否在网站根目录
  • AllowOverride All 是否配置
  • Apache 是否重启

2. 403 Forbidden

Require all granted

3. 404 页面

  • 正则写错
  • 文件路径不对

六、查看 rewrite 日志(调试用)

在 httpd.conf 中加:

LogLevel alert rewrite:trace3

然后:

tail -f /var/log/httpd/error_log

如果你用的是 CentOS + 宝塔 / LNMP / 某个框架(ThinkPHP、Laravel、WordPress),可以告诉我,我可以给你更精确的配置。

0 踩