htaccess重写除了索引文档之外的子域的路径

时间:2012-12-29 13:01:35

标签: apache .htaccess

我的网站中有以下结构,我需要将所有流量重定向到子域

结构:

domain.com/subdomain/
                 .../folder1/folder/1.txt
                 .../folder1/folder/2.txt
                 .../folder2/folder/1.txt
                 .../folder2/folder/1.txt
                 .../index.php

我想将除index.php或(domain.com/subdomain/)以外的所有流量重定向到子域

示例:

domain.com/subdomain/folder1/folder/1.txt    --->    subdomain.domain.com/folder1/folder/1.txt
domain.com/subdomain/folder1/folder/2.txt    --->    subdomain.domain.com/folder1/folder/1.txt

但是

domain.com/subdomain/index.php    --->    No redirect
domain.com/subdomain/    --->    No redirect

这就是我提出的:

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)$ http://subdomain.domain.com/$1 [NC]

这适用于所有请求,但我想排除/&来自此RewriteRule的index.php

谢谢!

1 个答案:

答案 0 :(得分:1)

你需要比你那里更多的东西。您必须先使用RewriteCond检查域名。模式^subdomain/?(index\.php)?$应该与子域根或index.php的请求匹配,有或没有/。从技术上讲,它也会匹配无效subdomainindex.php之间没有/,但无论如何都会产生404。

RewriteEngine On
# If the requested domain isn't already the subdomain...
RewriteCond %{HTTP_HOST} !^subdomain\. [NC]
# Rewrite it to the subdomain
# unless it is a request for index.php or /
RewriteRule ^subdomain/?(index\.php)?$ - [L]
RewriteRule ^subdomain/(.*) http://subdomain.com/$1 [L,R=301,NC]