温馨提示×

centos apache如何做伪静态

小樊
48
2026-09-18 03:07:21
栏目: 智能运维

在 CentOS + Apache 环境下做“伪静态”,通常是通过 mod_rewrite 模块和 .htaccess(或虚拟主机配置)来实现。下面按常见场景给你说明。


一、确认 Apache 已开启 rewrite 模块

1. 检查模块是否启用

httpd -M | grep rewrite

如果看到:

rewrite_module (shared)

说明已启用。

如果没有,启用它:

sudo yum install mod_rewrite
sudo systemctl restart httpd

二、允许 .htaccess 生效(关键)

Apache 默认可能不允许目录使用 .htaccess,需要修改配置。

1. 修改虚拟主机或 httpd 配置

编辑站点配置(例如):

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

确保有如下内容:

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

2. 重启 Apache

sudo systemctl restart httpd

三、使用 .htaccess 做伪静态(最常见)

在网站根目录创建或编辑 .htaccess:

RewriteEngine On

# 例子:将 /article/123.html 转发到 index.php?a=123
RewriteRule ^article/([0-9]+)\.html$ index.php?a=$1 [L]

常见示例

1. 全站入口(类似框架)

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

2. 隐藏 index.php(ThinkPHP / Laravel 类似)

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

四、直接写在 Apache 虚拟主机中(推荐生产环境)

比 .htaccess 性能更好:

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

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

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php [L]
</VirtualHost>

五、常见问题排查

1. 伪静态不生效

  • 检查 AllowOverride All
  • 检查 .htaccess 是否在正确目录
  • 查看错误日志:
tail -f /var/log/httpd/error_log

2. 403 / 404

  • 文件权限问题
  • rewrite 规则写错

六、示例(完整最小可用)

.htaccess:

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

访问:

/test/5

实际执行:

/test.php?id=5

如果你用的是 ThinkPHP / WordPress / Laravel / Discuz 等具体程序,可以告诉我,我可以直接给你对应伪静态规则。

0 踩