排列和组合htaccess

时间:2014-08-26 13:59:30

标签: php regex apache .htaccess mod-rewrite

有没有办法在htaccess中使用RewriteRule的排列?
例如,我有这个网址:

http://localmachine/index.php?c=category&brand=mybrand&country=mycountry&offer=yes&new=yes

重写网址应如下所示:

   http://localmachine/category/brand-mybrand/country-mycountry/offer-yes/new-yes

但我想在网址上的任何位置使用品牌,国家,优惠和新品 在网址中,我可以在任何位置拥有2,3或者所有位置。

这是我的htaccess:

RewriteRule ^([^/]+)/brand-([^/]+)/?$ index.php?c=$1&brand=$2 [QSA,L]
RewriteRule ^([^/]+)/gramaj-([^/]+)/?$ index.php?c=$1&gramaj=$2 [QSA,L]
RewriteRule ^([^/]+)/oferta-da/?$ index.php?c=$1&oferta=da [QSA,L]
RewriteRule ^([^/]+)/nou-da/?$ index.php?c=$1&nou=da [QSA,L]


RewriteRule ^([^/]+)/brand-([^/]+)/gramaj-([^/]+)/?$ index.php?c=$1&brand=$2&gramaj=$3 [QSA,L]
RewriteRule ^([^/]+)/brand-([^/]+)/nou-da/?$ index.php?c=$1&brand=$2&nou=da [QSA,L]
RewriteRule ^([^/]+)/brand-([^/]+)/oferta-da/?$ index.php?c=$1&brand=$2&oferta=da [QSA,L]
RewriteRule ^([^/]+)/gramaj-([^/]+)/nou-da/?$ index.php?c=$1&gramaj=$2&nou=da [QSA,L]
RewriteRule ^([^/]+)/gramaj-([^/]+)/oferta-da/?$ index.php?c=$1&gramaj=$2&oferta=da [QSA,L]
RewriteRule ^([^/]+)/gramaj-([^/]+)/brand-([^/]+)/?$ index.php?c=$1&gramaj=$2&brand=$3 [QSA,L]
RewriteRule ^([^/]+)/oferta-da/nou-da/?$ index.php?c=$1&oferta=da&nou=da [QSA,L]
RewriteRule ^([^/]+)/oferta-da/gramaj-([^/]+)/?$ index.php?c=$1&oferta=da&gramaj=$2 [QSA,L]
RewriteRule ^([^/]+)/oferta-da/brand-([^/]+)/?$ index.php?c=$1&oferta=da&brand=$2 [QSA,L]
RewriteRule ^([^/]+)/nou-da/gramaj-([^/]+)/?$ index.php?c=$1&nou=da&gramaj=$2 [QSA,L]
RewriteRule ^([^/]+)/nou-da/brand-([^/]+)/?$ index.php?c=$1&nou=da&brand=$2 [QSA,L]
RewriteRule ^([^/]+)/nou-da/oferta-da/?$ index.php?c=$1&nou=da&oferta=da [QSA,L]

1 个答案:

答案 0 :(得分:1)

这种基于递归的规则应该适合您:

RewriteEngine On

# rewrite /category to /index.php?c=category
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /index.php/?c=$1 [L,QSA]

# rewrite /category/brand-mybrand/country-mycountry/offer-yes/new-yes
# to /index.php/brand-mybrand/country-mycountry/offer-yes/new-yes?c=category
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^-]+.+)/?$ /index.php/$2?c=$1 [L,QSA]

# rewrite /index.php/brand-mybrand/country-mycountry/offer-yes/new-yes?c=category
# converts any /name-val/ to query parameter name=val in every rewrite
# stopping when there is no part left after /index.php
RewriteRule ^(index\.php)/([^-]+)-([^/]+)(/.*)?$ /$1$4?$2=$3 [L,QSA]

这将重写:

/category/brand-mybrand/country-mycountry/offer-yes/new-yes

到此:

/index.php?new=yes&offer=yes&country=mycountry&brand=mybrand&c=category

PS:我强烈建议您先单独测试此代码,然后在<2>规则下添加规则

相关问题