.htaccess重定向到任何目录中的index.php

时间:2014-08-29 18:25:21

标签: php .htaccess mod-rewrite redirect

我一直在研究我在php中创建的框架,其工作的基本部分是将所有url查询发送到根文件夹中的index.php。  我设法在我的.htaccess文件中的folloowing代码中执行此操作

# Turn rewriting on
Options +FollowSymLinks
RewriteEngine On
# Redirect requests to index.php
#RewriteRule ^(phpmyadmin)($|/) - [L]
RewriteRule ^(html)($|/) - [L]
RewriteCond %{REQUEST_URI} !=/index.php
RewriteCond %{REQUEST_URI} !.*\.png$ [NC]
RewriteCond %{REQUEST_URI} !.*\.jpg$ [NC]
RewriteCond %{REQUEST_URI} !.*\.css$ [NC]
RewriteCond %{REQUEST_URI} !.*\.gif$ [NC]
RewriteCond %{REQUEST_URI} !.*\.js$ [NC]
RewriteRule .* /index.php

将网站移动到其他文件夹时出现问题,例如

www.mydomain.com/subdir/{where the index.php is, along with htaccess}

它停止在这里工作。如果我将框架应用程序移动到子域也会发生同样的情况。

所以我试图修改.htaccess以正确地重写到index.php,其中.htaccess文件无论是在子目录还是子域中。我怎么能让.htaccess知道应用程序在子目录中并正确地重写它,所以位置的改变不会破坏.htaccess指向正确的文件?

 www.domain.com/{.htaccess+index.php + framework} => works properly
 www.subdom.domain.com/{.htaccess+index.php + framework}  => does not work
 www.domain.com/subdir/{.htaccess+index.php + framework} => does not work //send to www.domain.com/index.php
 localhost/projectname/{.htaccess+index.php + framework} =>does not work

如您所见,它需要将请求发送到index.php,其中htaccess也位于。

2 个答案:

答案 0 :(得分:3)

根据新示例进行编辑:

这样的事情怎么样?基本上检查以确保它不是文件,如果不是文件重定向到index.php

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond $1 !^(index\.php)
RewriteRule ^(.+)$ index.php [PT,L,QSA]

答案 1 :(得分:3)

您可以使用此技巧始终在当前目录的index.php中写入:

RewriteEngine On

# Generate BASE dynamically
# It compares REQUEST_URI variable (which is complete path) with the URI matched by 
# RewriteRule (which is relative to current path) and gets differential in
$ %{ENV:BASE} variable.
RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

RewriteRule ^(html)($|/) - [L]

# Redirect requests to %{ENV:BASE}index.php which is index.php of current directory
# It also makes sure index.php exists in current directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}%{ENV:BASE}index\.php -f [NC]
RewriteRule . %{ENV:BASE}index.php [L]