温馨提示×

apache2怎么配置伪静态

小樊
39
2026-10-02 04:58:39
栏目: 编程语言

在 Apache2 中配置“伪静态”(通常指用 .htaccess 实现 URL Rewrite),一般按下面步骤来。


一、开启 Rewrite 模块

1. 启用 mod_rewrite

sudo a2enmod rewrite

2. 重启 Apache

sudo systemctl restart apache2

二、修改 Apache 配置,允许 .htaccess 生效

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

编辑虚拟主机或全局配置

sudo nano /etc/apache2/apache2.conf

找到类似内容(如 /var/www/):

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

把:

AllowOverride None

改成:

AllowOverride All

保存后重启:

sudo systemctl restart apache2

三、编写 .htaccess 伪静态规则

在你的网站根目录(如 /var/www/html)创建或编辑:

nano /var/www/html/.htaccess

示例 1:基础 Rewrite(隐藏 index.php)

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

示例 2:ThinkPHP 风格

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

示例 3:自定义伪静态

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

访问:

/article/123.html

实际指向:

/article.php?id=123

四、常见问题排查

1. .htaccess 不生效

  • 确认 AllowOverride All
  • 确认 mod_rewrite 已启用
  • 确认文件名为 .htaccess(前面有点)

2. 500 错误

  • 检查 Rewrite 规则语法
  • 查看日志:
tail -f /var/log/apache2/error.log

3. 只想对某站点生效

在虚拟主机中配置:

<VirtualHost *:80>
    DocumentRoot /var/www/html
    <Directory /var/www/html>
        AllowOverride All
    </Directory>
</VirtualHost>

如果你告诉我 用的什么程序(WordPress / ThinkPHP / Laravel / 自定义),我可以直接给你一份可用的 .htaccess。

0 踩