温馨提示×

ubuntu apache如何设置伪静态

小樊
32
2026-09-17 09:08:42
栏目: 智能运维

在 Ubuntu 下使用 Apache 设置“伪静态”(通常指通过 .htaccess 或虚拟主机配置实现 URL Rewrite),一般步骤如下:


一、开启 Apache Rewrite 模块

sudo a2enmod rewrite
sudo systemctl restart apache2

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

1. 修改虚拟主机配置

编辑你的站点配置文件(示例):

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

<VirtualHost *:80> 中添加或修改:

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

如果是其他目录,请替换为你的网站根目录

2. 重启 Apache

sudo systemctl restart apache2

三、使用 .htaccess 设置伪静态

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

nano /var/www/html/.htaccess

示例 1:基础 Rewrite 规则

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

访问:

/article/123.html

实际指向:

/article.php?id=123

示例 2:隐藏 index.php(常见于 PHP 框架)

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

四、常见问题排查

1. .htaccess 不生效

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

2. 403 Forbidden

  • 检查目录权限
  • 检查 Apache 错误日志:
sudo tail -f /var/log/apache2/error.log

五、不使用 .htaccess(推荐生产环境)

直接在虚拟主机中写规则:

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

    <Directory /var/www/html>
        AllowOverride None
        Require all granted
    </Directory>

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

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

0