Htaccess参数重写和重定向

时间:2016-02-16 11:10:19

标签: .htaccess redirect mod-rewrite

我该如何重写?

somepage.php?parameter1 = value1& parameter2 = value2& parameter3 = value3 to SomePage的/参数1 / VALUE1 /参数2 / VALUE2 /参数3 /值3

并且还会重定向到较旧的索引网址。

另外,我希望它仅适用于其中两个参数,或者一个或者不参数。 我试过这个,但似乎没有那么好用:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]

RewriteRule ^([^/]*)/parameter1/([^/]*)$ $1.php?lang=$2 [PT]

2 个答案:

答案 0 :(得分:2)

您可以使用此通用规则将/somepage/n1/v1/n2/v2重写为/somepage.php?n2=v2&n1=v1

RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=302,NE,L]

RewriteRule ^(somepage)/([^/]*)/([^/]*)(/.*)?$ /$1/$4?$2=$3 [L,QSA,NC]
RewriteRule ^(somepage)/?$ $1.php [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]

答案 1 :(得分:1)

您必须为每种可能的情况创建一个规则,包含2个参数,1个参数和无参数。

RewriteEngine On
RewriteRule ^([^/]*)/parameter1/([^/]*)/parameter2/([^/]*)(/?)$ $1.php?
parameter1=$2&parameter2=$3 [NC]
RewriteRule ^([^/]*)/parameter1/([^/]*)(/?)$ $1.php?parameter1=$2 [NC]
RewriteRule ^([^/]*)(/?)$ $1.php [NC]

最后的(/?)也是为了捕捉链接以可能的斜线结束的情况。