显示没有父文件夹的特定(动态)URL。别管别人

Display particular (dynamicaly) URL without parent folder. Leave The Others Alone

我今天开始学习重写

首先是我的链接示例

Index.php?action=pictures
Index.php?action=pictures&type=kitchen
Index.php?action=pictures&type=ceiling
Index.php?action=services
Index.php?action=services&type=shower
Index.php?action=services&type=windows

在我的 .htaccess 文件中我有这个

RewriteEngine On
RewriteBase /
#Do not Rewrite files or folders
RewriteCond %{REQUEST_FILENAME} -f [NC,OR]
RewriteCond %{REQUEST_FILENAME} -d [NC]
RewriteRule ^(.*?)$  [L]

#Ordinary
RewriteRule ^\.htaccess$ .htaccess [F]
RewriteRule ^(.*)/(.*)/?$ Index.php?action=&type= [L]
RewriteRule ^(.*)/?$ Index.php?action= [L]

将 URL 重写为

localhost/pictures
localhost/pictures/kitchen
localhost/pictures/ceiling

localhost/services
localhost/services/shower
localhost/services/windows

//etc

我希望我的所有链接都按原样工作,但不需要父文件夹的服务除外 /services/。 结果:

localhost/pictures
localhost/pictures/kitchen
localhost/pictures/ceiling

localhost/services
localhost/shower
localhost/window

我试图重写 .htaccess,但要么只有父文件夹可以工作,要么只有子文件夹。 我试着添加这个,但我知道它匹配所有内容...

RewriteRule ^(.*)/?$ Index.php?action=services&type= [L]

不过我可以像这样硬编码

RewriteRule ^window/?$ Index.php?action=services&type=window [L]

想要一些动态的东西。如果文件夹服务 -> 显示没有文件夹但仍然可以看到 localhost/services! 可能吗?

这样想:Apache 如何知道一个特定的字符串是一个动作,还是一种服务?

嗯,你有三个选择:

  • 我们对服务类型进行硬编码。任何与类型不匹配的都必须是一个动作。
  • 我们对操作进行硬编码。因此,任何与操作不匹配的都必须是一种服务。
  • Apache 无法知道:我们将它提供给脚本,脚本可能会施展魔法来找出这个字符串是什么。

在你的情况下,硬编码动作似乎是最好的主意,至少当动作是静态的时候。

RewriteRule ^(.*)/(.*)/?$ Index.php?action=&type= [L]
RewriteRule ^(pictures|services)/?$ Index.php?action= [L]
RewriteRule ^(.*)/?$ Index.php?action=services&type= [L]