.htaccess - 默默地重写/重定向一切到内部子文件夹

时间:2014-10-16 13:04:37

标签: apache .htaccess mod-rewrite redirect

我们说我有这个www.example.com网站结构:

/srv/http/
/srv/http/site/index.php
/srv/http/site/stuff.php

我希望以下重写/重定向发生:

www.example.com/index.php - >重定向到 - > www.example.com/site/index.php - >但是用户看到 - > www.example.com/index.php

www.example.com/stuff.php - >重定向到 - > www.example.com/site/stuff.php - >但是用户看到 - > www.example.com/stuff.php

通常,www.example.com/之后的所有内容都会重定向到www.example.com/site/。但是用户在浏览器中看到了原始URL。

我在互联网上环顾四周,但没有设法弄清楚在这种特殊情况下应该使用什么。

我尝试重写所有内容:

RewriteEngine On
RewriteRule ^$ /site [L]

index.php消失,并向用户显示www.example.com/site/

如何使用.htaccess解决此问题?

3 个答案:

答案 0 :(得分:8)

您需要捕获传入服务器的URL请求,如下所示:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/site/
RewriteRule ^(.*)$ /site/$1 [L,QSA]

QSA(最终)也将查询字符串附加到重写的网址

答案 1 :(得分:6)

与@guido建议相同,但使用负向前瞻

略微缩短
RewriteEngine On
RewriteRule ^(?!site/)(.*)$ site/$1 [L]

注意:我没有使用QSA标记,因为我们没有在替换网址的查询字符串中添加其他参数。默认情况下,Apache会将原始查询字符串与替换URL一起传递。

http://www.example.com/index.php?one=1&two=2 

将在内部重写为

http://www.example.com/site/index.php?one=1&two=2

如果你真的想在查询字符串中为每次重写添加一个特殊参数(例如:mode=rewrite),那么你可以使用QSA查询字符串追加标志< / p>

RewriteEngine On
RewriteRule ^(?!site/)(.*)$ site/$1?mode=rewrite [L,QSA]

然后,这会将mode=rewrite与原始查询字符串

组合在一起
http://www.example.com/index.php?one=1&two=2 

http://www.example.com/site/index.php?mode=rewrite&one=1&two=2 

答案 2 :(得分:1)

RewriteEngine On

RewriteRule ^(.*)$ site/index.php?var=$1 [L]

使用此规则,我将所有请求传递给site / index.php,因此您可以通过$ _GET ['var']获取请求的uri,然后您将使index.php服务于请求的URL在用户浏览器中没有更改url的场景后面。侨