温馨提示×

ubuntu apache2如何设伪静态

小樊
45
2026-09-11 03:00:38
栏目: 智能运维

在 Ubuntu 上使用 Apache2 设置伪静态(URL Rewrite),通常是通过 mod_rewrite 模块实现的。下面按常见场景一步步说明。


一、开启 rewrite 模块

sudo a2enmod rewrite
sudo systemctl restart apache2

确认是否已启用:

apache2ctl -M | grep rewrite

看到 rewrite_module 即成功。


二、修改 Apache 配置(关键)

1. 修改站点配置(推荐方式)

编辑你的站点配置文件(以默认站点为例):

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

<VirtualHost *:80> 内加上:

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

⚠️ 重点是 AllowOverride All,否则 .htaccess 不生效

保存后重启 Apache:

sudo systemctl restart apache2

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

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

sudo nano /var/www/html/.htaccess

示例 1:把所有请求重写到 index.php(常见框架)

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

示例 2:将 article/123 伪静态为 article.php?id=123

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

访问:

http://yourdomain.com/article/123

四、直接在 Apache 配置中写 Rewrite(可选)

也可不写 .htaccess,直接写在 <VirtualHost><Directory> 里:

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

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

五、常见错误排查

1. .htaccess 不生效

  • 检查 AllowOverride All
  • 重启 Apache
  • 确认 .htaccess 在正确目录

2. 404 或 500

  • 查看错误日志:
sudo tail -f /var/log/apache2/error.log

3. 多站点

每个站点都要单独配置 AllowOverride All


六、常见 CMS 伪静态示例

WordPress

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

如果你能告诉我:

  • 使用的是 什么程序(WordPress / ThinkPHP / Laravel / 自写 PHP)
  • 伪静态规则想要 什么效果

我可以直接帮你写完整配置。

0