将子域重写为文件夹并将该文件夹重定向到子域

时间:2015-03-22 22:50:22

标签: apache .htaccess mod-rewrite redirect

我有重写规则,将所有用户从random.example.com发送到/random/

但我想这样做,以致如果用户直接访问/random/,它会将它们重定向(重定向不重写)到子域。

这就是我所拥有的:

RewriteEngine on  
# NO WWW
RewriteCond %{HTTP_HOST} ^www.example.com [NC] 
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

# USE RANDOM SUB DOMAIN WITH CONTENT IN SUB FOLDER
RewriteCond %{HTTP_HOST} random.example.com$
RewriteCond %{REQUEST_URI} !^/random
RewriteRule ^(.*)$ /random/$1 [L]

# SEND SNOOPERS AT SUB FOLDER TO SUB
Redirect ^(.*)$/random/$1 %{HTTP_HOST}random.example.com$

但是,我在最后一行收到服务器500错误。基本上它需要处理随机目录中出现的任何URL,例如:

http://example.com/random -> http://random.example.com/

http://example.com/random/fakeplace/ -> http://random.example.com/fakeplace/

http://example.com/random?id=4 -> http://random.example.com/?id=4

1 个答案:

答案 0 :(得分:1)

最后一行的语法错误。您甚至将RewriteRule与Redirect混合使用。试试这些规则。我改变了一些事情。

RewriteEngine on  
# NO WWW
RewriteCond %{HTTP_HOST} ^www.example.com [NC] 
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

# USE RANDOM SUB DOMAIN WITH CONTENT IN SUB FOLDER
RewriteCond %{HTTP_HOST} ^random\.example\.com$
RewriteRule !^random/? random%{REQUEST_URI} [NC,L]

RewriteCond %{THE_REQUEST} \s/random/([^\s]*) [NC]
RewriteRule ^ http://random.example.com/%1 [R=301,L]