使用正则表达式进行多次htaccess重定向

时间:2017-01-19 17:12:46

标签: php regex .htaccess redirect

我需要创建重定向:

www.mysite.com/out/cars/到https://cars.example.com/?aid=123(不工作)

RewriteCond %{THE_REQUEST} /out/cars [NC]
RewriteRule ^ https://cars.othersite.com/?aid=123 [NE,L,R=302]

www.mysite.com/out/cars/volvo/到https://cars.example.com/volvo/?aid=123(有效)

RewriteCond %{THE_REQUEST} /out/cars/([^/]+) [NC]
RewriteRule ^ https://cars.othersite.com/%1/?aid=123 [NE,L,R=302]

www.mysite.com/out/cars/volvo/vagon/至https://cars.example.com/volvo/vagon/?aid=123(正常)

RewriteCond %{THE_REQUEST} /out/cars/([^/]+)/([^/]+) [NC]
RewriteRule ^ https://cars.othersite.com/%1/%2/?aid=123 [NE,L,R=302]

www.mysite.com/out/bikes/到https://bikes.example.com/?aid=123(不工作)

RewriteCond %{THE_REQUEST} /out/bikes [NC]
RewriteRule ^ https://bikes.othersite.com/?aid=123 [NE,L,R=302]

www.mysite.com/out/bikes/suzuki/到https://bikes.example.com/suzuki/?aid=123(不工作)

RewriteCond %{THE_REQUEST} /out/bikes/([^/]+) [NC]
RewriteRule ^ https://bikes.othersite.com/%1/?aid=123 [NE,L,R=302]

www.mysite.com/out/bikes/suzuki/volusia至https://bikes.example.com/suzuki/volusia/?aid=123(作品)

RewriteCond %{THE_REQUEST} /out/bikes/([^/]+)/([^/]+) [NC]
RewriteRule ^ https://bikes.othersite.com/%1/%2/?aid=123 [NE,L,R=302]

www.mysite.com/out/atv/bmw/black/big/best/至https://atv.example.com/bmw/black/big/best/?aid=123(正常)

RewriteCond %{THE_REQUEST} /out/atv/([^/]+)/([^/]+)/([^/]+)/ [NC]
RewriteRule ^ http://atv.example.com/%1/%2/%3/?aid=123 [NE,L,R=302]

事情是,有些规则有效,但不是全部。我猜他们会以某种方式干涉,但我试图改变我所能做到的,并且没有任何效果100%:(

例如,会发生什么:

www.mysite.com/out/bikes/suzuki/

重定向到:

https://bikes.example.com/suzuki/%20http/?aid=123

等。 :(

有人可以帮忙吗?非常感谢你提前!

2 个答案:

答案 0 :(得分:2)

也许更简单的正则表达式仍然足够? (从示例中推断出明显的规则,因为它们没有明确说明)

RewriteCond %{THE_REQUEST} .*?/out/(cars|bikes|atv)/?(.*) [NC]
RewriteRule ^ http://$1.example.com/$2?aid=123 [NE,L,R=302]

https://regex101.com/r/vp9jrA/2

答案 1 :(得分:2)

尝试:

RewriteRule ^out/cars/?$ https://cars.othersite.com/?aid=123 [NC,NE,L,R=302]
RewriteRule ^out/cars/([^/]+)/?$ https://cars.othersite.com/$1/?aid=123 [NC,NE,L,R=302]
RewriteRule ^out/cars/([^/]+)/([^/]+)/?$ https://cars.othersite.com/$1/$2/?aid=123 [NC,NE,L,R=302]
RewriteRule ^out/bikes/?$ https://bikes.othersite.com/?aid=123 [NC,NE,L,R=302]
RewriteRule ^out/bikes/([^/]+)/?$ https://bikes.othersite.com/$1/?aid=123 [NC,NE,L,R=302]
RewriteRule ^out/bikes/([^/]+)/([^/]+)/?$ https://bikes.othersite.com/$1/$2/?aid=123 [NC,NE,L,R=302]
RewriteRule ^out/atv/([^/]+)/([^/]+)/([^/]+)/?$ http://atv.example.com/$1/$2/$3/?aid=123 [NC,NE,L,R=302]