首页 > 解决方案 > .htaccess mod_rewrite 具有 3 个目录级别

问题描述

如何在 Htaccess 上管理 3 个子目录级别?
解释:

RewriteRule to *category.php?category=$1*

RewriteRule to *type.php?category=$1&type=$2*

RewriteRule to *company.php?category=$1&type=$2&company=$3*

.htaccess 文件位于初始根文件夹(其中 index.php)

下一个是最好的方法吗?

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/.]+)(?:/)?$ /category.php?category=$1 [L]
RewriteRule ^([^/.]+)/([^/.]+)(?:/)?$ /type.php?category=$1&type=$2 [L]
RewriteRule ^([^/.]+)/([^/.]+)/([^/.]+)(?:/.*)?$ /company.php?category=$1&type=$2&company=$3 [L]

标签: regexapache.htaccessmod-rewriteurl-rewriting

解决方案


你很接近。请注意,RewriteCond仅适用于下一个立即RewriteRule数,因此您的检查!-f将仅用于第一条规则。您可以有一个单独的规则来丢弃所有针对现有文件和目录的请求。

RewriteEngine On

# skip all files and directories from rewrite rules below
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([\w-]+)/?$ category.php?category=$1 [L,QSA]
RewriteRule ^([\w-]+)/([\w-]+)/?$ type.php?category=$1&type=$2 [L,QSA]
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/?$ company.php?category=$1&type=$2&company=$3 [L,QSA]

推荐阅读