温馨提示×

Apache如何开启伪静态

小樊
46
2026-08-16 12:08:50
栏目: 编程语言

Apache 中开启“伪静态”(URL Rewrite),通常是指使用 mod_rewrite 模块,把动态 URL(如 index.php?id=1)伪装成静态 URL(如 /article/1.html)。下面按常见场景一步步说明。


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

1️⃣ 检查 mod_rewrite 是否启用

apache2ctl -M | grep rewrite

httpd -M | grep rewrite

如果看到:

rewrite_module (shared)

说明已启用 ✅


2️⃣ 若未启用(Ubuntu / Debian)

sudo a2enmod rewrite
sudo systemctl restart apache2

CentOS / RHEL

vi /etc/httpd/conf/httpd.conf

确保有:

LoadModule rewrite_module modules/mod_rewrite.so

然后重启:

systemctl restart httpd

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

Apache 默认可能不允许 .htaccess 覆盖规则

修改虚拟主机或主配置

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

⚠ 如果是 Ubuntu,通常在:

/etc/apache2/sites-enabled/000-default.conf

修改后重启 Apache:

sudo systemctl restart apache2

三、使用 .htaccess 开启伪静态(最常用)

1️⃣ 在网站根目录创建 .htaccess

vi /var/www/html/.htaccess

2️⃣ 基础伪静态规则示例

RewriteEngine On

# 将 /article/1 转发给 index.php
RewriteRule ^article/([0-9]+)$ index.php?id=$1 [L,QSA]

访问:

http://example.com/article/1

实际执行:

index.php?id=1

四、常见伪静态规则示例

✅ 去掉 index.php(ThinkPHP / Laravel)

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

✅ 伪静态 HTML 页面

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

访问:

/news-123.html

✅ 全站强制 HTTPS

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

五、常见问题排查

❌ .htaccess 不生效

✅ 检查:

  • AllowOverride All
  • 是否重启 Apache
  • .htaccess 是否在正确目录

❌ 500 错误

✅ 检查:

  • RewriteRule 语法错误
  • 模块未启用

查看错误日志:

tail -f /var/log/apache2/error.log

六、总结(最简流程)

1. 启用 mod_rewrite
2. 设置 AllowOverride All
3. 重启 Apache
4. 编写 .htaccess

如果你用的是 宝塔 / LNMP / 某个 CMS(WordPress、ThinkPHP、帝国、织梦),可以告诉我具体环境,我可以给你 专用伪静态规则

0