1

I am building a website that will have categories, and I want to access them through the URL.

Example:
http://website.com/category-1/category-2

There is no limit to the number of categories that there could be, so there could be 1 or their could be 1,000.

What would I have to do to make a rewrite that could support many categories? I will then be passing it to php to parse.

Here is what I have tried (Gives 404):

Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ /category.php?params=$1 [L,QSA]
4

2 回答 2

1

如果您不想依赖 PHP,以下规则集可能对您有用:

RewriteEngine on
RewriteRule ^([^/]+)/(.+)$ /$2?catstr[]=$1 [QSA,N] 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/]+)$ /category.php?catstr[]=$1&category=1 [QSA,L]

一个简短的解释:

第一条规则将匹配 / directory / anything并重定向到任何东西?catstr[]= directory。QSA 标志将强制它保留查询字符串参数,而 N 标志将强制 rewrite_rule 倒回规则集。

最后一条规则就是你的最后一条。

因此,按顺序,点击 /a/b/c/def 的人将在内部被抛出(这些查询将不会执行):

/b/c/def?catstr[]=a

/c/def?catstr[]=b&catstr[]=a

/def?catstr[]=c&catstr[]=b&catstr[]=a

/category.php?catstr[]=def&catstr[]=c&catstr[]=b&catstr=a&category=1

值得注意的是,顺序将被颠倒。这可以对您有利,并且是一项功能,而不是错误。如何将第一个重写规则以正确的方式排序的练习留给读者练习。

然后,您可以使用$_GET['catstr']PHP 中的数组来使用 URI 的每一段。

于 2013-05-25T22:51:14.413 回答
0

我想我明白了,这就是我所拥有的。

.htaccess:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ /category.php?catstr=$1&category=1 [L,QSA]

PHP:

<?php
$categories = explode("/", $_GET["catstr"]);
print_r($categories);
于 2013-05-25T22:29:29.427 回答