下面以 Linux 下 Apache2 为例,系统讲一下 伪静态(URL Rewrite) 的配置方法,适用于常见场景(如 ThinkPHP、WordPress、自定义路由等)。
Apache 伪静态依赖 mod_rewrite 模块。
sudo a2enmod rewrite
sudo systemctl restart apache2
sudo vim /etc/httpd/conf/httpd.conf
确保有以下内容(没有被注释):
LoadModule rewrite_module modules/mod_rewrite.so
然后重启:
sudo systemctl restart httpd
找到你的站点配置(以 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:
vim /var/www/html/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
含义:
index.php<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
如果你不想用 .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>
AllowOverride 是否为 AllRewriteEngine OnDocumentRoot.htaccess 没覆盖到子目录如果你能告诉我:
我可以直接给你 可复制的配置。