我在使用以下工作时遇到了一些麻烦:
<IfModule mod_rewrite.c>
DirectoryIndex index.php
Options +FollowSymLinks
RewriteEngine On
# If the file is not found in web
RewriteCond web/$1 -f [NC] #<-- This line seems to be the problem.
RewriteRule ^(.*)$ web/$1 [L]
# Then rewrite it to index.php
RewriteRule ^(.*)$ index.php [L,QSA]
</IfModule>
想法是检查文件是否存在于web目录中,如果不存在,则将请求路由到index.php。
上面有问题的行似乎找到了正确的网址,但它无法识别该文件是否存在。
例如:
http://localhost/img.gif --> /www/web/img.gif
http://localhost/subdir/file.doc --> /www/web/subdir/file.doc
http://localhost/user/add --> /www/index.php
http://localhost/invalidurl --> /www/index.php
但是,我无法正确提供静态资源,它们都被路由到index.php。
我还希望保持所有网址的相对性;所以我可以在不编辑代码的情况下重复使用此代码。
如果我访问img.gif:
,以下.htaccess会出现内部服务器错误<IfModule mod_rewrite.c>
DirectoryIndex index.php
Options +FollowSymLinks
RewriteEngine On
# If the file is not found in web
#RewriteCond web/$1 -f [NC] #<-- This line seems to be the problem.
RewriteRule ^(.*)$ web/$1 [L]
# Then rewrite it to index.php
#RewriteRule ^(.*)$ index.php [L,QSA]
</IfModule>
当访问img.gif时,此.htaccess重定向到http://localhost/C:/absolute/path/to/web/img.gif:
<IfModule mod_rewrite.c>
DirectoryIndex index.php
Options +FollowSymLinks
RewriteEngine On
# If the file is not found in web
#RewriteCond web/$1 -f [NC] #<-- This line seems to be the problem.
RewriteRule ^(.*)$ web/$1 [R]
# Then rewrite it to index.php
#RewriteRule ^(.*)$ index.php [L,QSA]
</IfModule>
我的结论是,它正在使路径正确,但是一些奇怪的事情导致它做了一些完全奇怪的事情(我甚至不知道为什么它有内部服务器错误 - 应该找不到404)。< / p>
答案 0 :(得分:1)
好的我明白了:
当您进行重写时,请记住在内部调用重写的URL。 因此,您基本上必须使用大多数不同的值重新处理.htaccess。
因此,在您的示例中:http://localhost/img.gif
被定向到http://localhost/web/img.gif
,然后被最后一条规则定向到http://localhost/index.php
。
我会尝试这个(将最后一条规则替换为:)
RewriteCond %{SCRIPT_NAME} !^/web/
RewriteRule ^(.*)$ index.php [L]
(注意:由于您未触摸查询字符串,因此不需要[QSA],因此会按原样传递。)
修改:
怎么样?# If the file is not found in web
RewriteCond web/$1 !-f [NC]
# And we don't ask for /web/something at the beginning (Avoid infinite loops since you'll try to call web/image.gif and we don't want to test /web/web/image.gif and fail to index.php
RewriteCond %{SCRIPT_NAME} !^/web/
#Rewrite it to index.php
RewriteRule ^(.*)$ index.php [R,L]
# If the file is found in web
RewriteCond web/$1 -f [NC]
# And we don't ask for /web/something at the beginning (Avoid infinite loops since you'll try to call web/image.gif and we don't want to test /web/web/image.gif and fail to index.php
RewriteCond %{SCRIPT_NAME} !^/web/
#Then point to web/image.gif
RewriteRule ^(.*)$ web/$1 [L]