温馨提示×

怎样配置apache2伪静态

小樊
46
2026-09-27 15:50:18
栏目: 编程语言

下面以 Linux 下 Apache2 为例,系统讲一下 伪静态(URL Rewrite) 的配置方法,适用于常见场景(如 ThinkPHP、WordPress、自定义路由等)。


一、开启 mod_rewrite 模块

Apache 伪静态依赖 mod_rewrite 模块。

Ubuntu / Debian

sudo a2enmod rewrite
sudo systemctl restart apache2

CentOS / RHEL

sudo vim /etc/httpd/conf/httpd.conf

确保有以下内容(没有被注释):

LoadModule rewrite_module modules/mod_rewrite.so

然后重启:

sudo systemctl restart httpd

二、修改 Apache 配置(关键)

1️⃣ 允许 .htaccess 生效

找到你的站点配置(以 Ubuntu 为例):

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

在 <VirtualHost> 中添加或修改:

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

然后重启 Apache:

sudo systemctl restart apache2

⚠️ 如果不设置 AllowOverride All,.htaccess 是不会生效的。


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

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

vim /var/www/html/.htaccess

✅ 基础伪静态示例

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

含义:

  • 不是真实文件
  • 不是真实目录
  • 全部转发给 index.php

四、常见框架示例

✅ ThinkPHP

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

✅ WordPress

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

五、直接在 Apache 配置中写(不用 .htaccess)

如果你不想用 .htaccess:

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

    <Directory /var/www/html>
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php/$1 [QSA,L]
    </Directory>
</VirtualHost>

六、常见问题排查

❌ 伪静态不生效

  • 是否重启 Apache
  • AllowOverride 是否为 All
  • 是否有 RewriteEngine On

❌ 404

  • 检查是否指向正确的入口文件
  • 检查 DocumentRoot

❌ 首页正常,内页 404

  • 通常是 .htaccess 没覆盖到子目录

如果你能告诉我:

  • 系统(Ubuntu / CentOS)
  • Apache 版本
  • 使用的程序(TP / WP / 自写)

我可以直接给你 可复制的配置。

0 踩