如何仅在这些情况下重写?

时间:2013-11-02 18:15:09

标签: apache .htaccess mod-rewrite url-rewriting

我需要一种方法来重定向所有以及仅以文件夹开头的网址:“home /”“car /”,从example.com到jp.example .COM。

例如:

example.com/home/test.html ---> jp.example.com/home/test.html
example.com/car/test.html ---> jp.example.com/car/test.html
jp.example.com/home/second-test.html ---> jp.example.com/home/second-test.html
jp.example.com/third-test.html ---> example.com/third-test.html 

我正在使用此代码:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^jp.example.com$
RewriteRule ^(.*)$ http://jp.example.com/$1 [R=301]

但它不起作用,因为它将example.com中的所有网址重写为jp.example.com

2 个答案:

答案 0 :(得分:0)

您只需检查请求的URI是以/home还是/car开头,如下所示:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^jp.example.com$ [NC]
RewriteCond %{REQUEST_URI} ^(/home|/car)(/.*)?$ [NC]
RewriteRule ^(.*)$ http://jp.example.com/$1 [R=301]

答案 1 :(得分:0)

您可以使用以下规则:

RewriteEngine on

# conditions 1 & 2
RewriteCond %{HTTP_HOST} ^(www\.)?(example\.com)$ [NC]
RewriteRule ^(home|care)/ http://jp.%1%{REQUEST_URI} [L,NC,NE,R=301]

# conditions 3
RewriteCond %{HTTP_HOST} ^jp\.example\.com$ [NC]
RewriteRule ^(home)/second_(test\.html)$ /$1/$2 [L,NC,R=301]

# conditions 4
RewriteCond %{HTTP_HOST} ^jp\.(example\.com)$ [NC]
RewriteRule ^(third-test\.html)$ http://%1/$1 [L,NC,R=301]