温馨提示×

apache2如何开启伪静态

小樊
43
2026-10-05 03:27:00
栏目: 编程语言

在 Apache2 中开启“伪静态”(通常是用 .htaccess + mod_rewrite 实现 URL 重写),一般按下面步骤操作:


一、开启 mod_rewrite 模块

Ubuntu / Debian

sudo a2enmod rewrite
sudo systemctl restart apache2

CentOS / RHEL

sudo vi /etc/httpd/conf/httpd.conf

确认有:

LoadModule rewrite_module modules/mod_rewrite.so

然后重启:

sudo systemctl restart httpd

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

Apache 默认可能不允许目录使用 .htaccess。

编辑虚拟主机或主配置文件:

sudo vi /etc/apache2/sites-available/000-default.conf

(或你的站点配置文件)

在 <VirtualHost> 中添加:

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

然后重启 Apache:

sudo systemctl restart apache2

三、编写 .htaccess 伪静态规则

在项目根目录(如 /var/www/html)创建 .htaccess:

RewriteEngine On

# 例子:把 /article/123 重写为 index.php?a=123
RewriteRule ^article/([0-9]+)$ index.php?a=$1 [L]

四、常见框架示例

ThinkPHP

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

WordPress

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

五、排查问题

  1. 404 或无效果
    • 确认 AllowOverride All
    • 确认 mod_rewrite 已启用
  2. 查看错误日志:
tail -f /var/log/apache2/error.log

如果你用的是 具体框架(ThinkPHP / Laravel / WordPress) 或 具体系统(Ubuntu/CentOS),可以告诉我,我给你精确配置。

0 踩