htaccess – redirect到子目录时的规范URL

我一直在玩这个问题很长一段时间,但无法find如何实现我想要的方式。 我希望用户来我的网站test.com到达位于子目录www立即,我能够做index.php。 但是当URL是test.com/www我希望它只是test.com。

代码片段:

.htaccess在/

RewriteRule ^(.*)$ /www/$1 [L] 

.htaccess在/ www

 RewriteCond %{REQUEST_URI} ^/www.*$ RewriteRule ^/www/(.*)$ /$1 [L] 

给我500内部错误。

更新:我来到一个解决scheme感谢@Justin Iurman的答案:

.htaccess在/ www

 RewriteCond %{THE_REQUEST} \ /www/?(.*)\ HTTP/ [NC] RewriteRule ^(.*)$ /%1 [R=301,L] 

还有一个问题。 在服务器机器上,我有多个网站,我想根据根.htaccess文件中的HTTP_HOSTvariables提供文件。 我将访问test.com的用户redirect到正确的目录(比如testing),但我希望URL test.com可以redirect到test.com。 目录testing包含用户被redirect的目录www,并且由于上面的解决scheme,它不会粘在URL上。 我想在web服务器的根目录下编辑.htaccess文件,所以我没有任何依赖项目的网站的域名。

解决了

.htaccess在web服务器根目录下:

 <IfModule mod_rewrite.c> RewriteEngine On # Redirect test.com/test (and everything into test folder) to test.com root RewriteCond %{HTTP_HOST} ^test\.com$ [NC] RewriteCond %{THE_REQUEST} \ /test/? [NC] RewriteRule ^.*$ / [R=301,L] # Forward (internally rewrite) test.com/one/example/page to test.com/test/www/one/example/page RewriteCond %{HTTP_HOST} ^test\.com$ [NC] RewriteRule ^(.*)$ /test/www/$1 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d </IfModule> 

“test”目录下的.htaccess文件:

 <IfModule mod_rewrite.c> RewriteEngine On # allow /test in URL only for certain filetypes RewriteRule ^(.*\.(pdf|js|ico|gif|jpg|png|css|rar|zip|tar\.gz))$ /test/www/$1 [L] # allow /test on localhost RewriteCond %{HTTP_HOST} ^localhost$ [NC] RewriteRule ^(.*)$ /test/www/$1 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d </IfModule> 

非常感谢Justin!

做你想做的事时,你必须避免无限循环。

把这段代码放到你的htaccess中

 RewriteEngine on RewriteCond %{THE_REQUEST} \ /www/?(.*)\ HTTP/ [NC] RewriteRule . /%1 [R=301,L] RewriteRule ^(.*)$ /www/$1 [L] 

编辑:考虑到你的更新,这里是新的代码

 RewriteEngine on # Redirect test.com/test (and everything into test folder) to test.com root RewriteCond %{HTTP_HOST} ^test.com$ [NC] RewriteCond %{THE_REQUEST} \ /test/? [NC] RewriteRule . / [R=301,L] # Forward (internally rewrite) test.com/one/example/page to test.com/test/www/one/example/page RewriteCond %{HTTP_HOST} ^test.com$ [NC] RewriteRule ^(.*)$ /test/www/$1 [L]