重写文件夹并删除末尾的尾部斜杠

时间:2015-06-13 19:49:17

标签: php apache .htaccess mod-rewrite

我试图在URL /文件夹的末尾只有一个没有尾部斜杠的URL,但同时我想重写这个文件夹以使用动态页面,例如:

如果我有:

mydomain.com/folder
mydomain.com/folder/

mydomain.com/folder/second
mydomain.com/folder/second/

然后我想只打开“mydomain.com/folder”和“mydomain.com/folder/second”,这个URL应该打开一个动态页面。这是我正在尝试的,但它不起作用,它崩溃了我的页面:

RewriteEngine On
RewriteRule ^(.*)/$   /$1 [L]
RewriteRule ^(.*)$    includes/category.php?url=$1&pageType=category [L] 

RewriteRule ^(.*)/(.*)/$  /$1/$2 [L]
RewriteRule ^(.*)/(.*)$   includes/subcategory.php?url=$1&pageType=subCategory [L] 

我做错了什么?你可以帮我运行正确的语法吗?

2 个答案:

答案 0 :(得分:1)

您需要重定向尾随斜杠网址,而不是仅重写它们。您可能还需要为规则添加一些条件:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ /includes/category.php?url=$1&pageType=category [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)$ /includes/category.php?url=$1&pageType=subCategory [L]

答案 1 :(得分:0)

RewriteEngine On
RewriteRule ^([^\/]+)/?$    includes/category.php?url=$1&pageType=category [L] 

RewriteRule ^([^\/]+)/([^\/]+)/?$   includes/subcategory.php?url=$1&pageType=subCategory [L] 

您还可以添加以下条件(在重写之前)以从这些规则中排除真实文件和文件夹:

 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d