在 Apache2 中设置伪静态(URL Rewrite),核心是使用 mod_rewrite 模块。下面按常见场景一步步说明。
sudo a2enmod rewrite
sudo systemctl restart apache2
sudo httpd -M | grep rewrite
如果没有开启:
sudo vi /etc/httpd/conf/httpd.conf
取消注释或添加:
LoadModule rewrite_module modules/mod_rewrite.so
然后重启:
sudo systemctl restart httpd
伪静态通常写在 .htaccess 中,需要确保目录允许覆盖。
<Directory /var/www/html>
AllowOverride All
Require all granted
</Directory>
修改后重启 Apache。
在网站根目录创建或编辑 .htaccess 文件:
RewriteEngine On
# 访问 /article/123 实际指向 /article.php?id=123
RewriteRule ^article/([0-9]+)$ article.php?id=$1 [L]
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.html [L]
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
<Directory /var/www/html>
AllowOverride All
Require all granted
</Directory>
RewriteEngine On
RewriteRule ^article/([0-9]+)$ article.php?id=$1 [L]
</VirtualHost>
| 标志 | 含义 |
|---|---|
L |
最后一条规则 |
R=301 |
永久重定向 |
QSA |
保留原有查询参数 |
NC |
忽略大小写 |
查看是否生效:
apache2ctl -S
开启日志调试(调试完记得关闭):
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3
如果你能提供:
我可以给你完全对应的一套配置。