如何通过.htaccess创建动态目录和子目录

时间:2017-02-16 20:41:22

标签: php apache .htaccess

我正在尝试创建一个htaccess脚本,它将为零个,一个或两个变量创建目录。

我正在使用的文件接受以下2个get变量。制作和模型。

这是一个3步页面。我目前的页面位于/new.php。该页面允许用户选择第一个变量(在我的例子中,是车辆制造商)。通过在此页面上选择一个品牌,用户将被带到/new.php?make=Acura。此页面现在显示所有Acura型号的列表。从这里,用户可以单击模型,它们将被定向到/new.php?make=Acura&model=TLX。他们现在可以选择一个子模型,并将被带到一个信息页面。

所以我试图获得:

new.php to go to /new/
new.php?make=XMake to go to /new/XMake/
and new.php?make=XMake&model=XModel to go to /new/XMake/XModel/

据我所知,这是我的代码:

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^new/(.*)$ new.php?make=$1 [L,NC]

然而,我在此之后添加的任何变量似乎打破了第一个目录?这是为什么?

2 个答案:

答案 0 :(得分:1)

您可以在站点根目录中使用这些规则.htaccess:

Options -MultiViews
RewriteEngine On

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

RewriteRule ^new/([\w-]+)/([\w-]+)/?$ new.php?make=$1&model=$2 [L,NC,QSA]

RewriteRule ^new/([\w-]+)/?$ new.php?make=$1 [L,NC,QSA]

RewriteRule ^new/?$ new.php [L,NC]

答案 1 :(得分:1)

规则的顺序很重要。在开头使用此规则时,任何请求/new//new/XMake/new/XMake/XModel/都会匹配,并忽略以下规则。

为了与其他规则相匹配,必须首先采用更具体的规则,例如

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^new/(.+?)/(.+)$ new.php?make=$1&model=$2 [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^new/(.+)$ new.php?make=$1 [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^new/$ new.php [L,NC]
相关问题