我一直试图模仿nodejs / express如何使用他们的路由。我将所有流量转发到index.php
以处理路由(使用AltoRouter)。
我的文件结构是这样的:
-/
--public/
|- assets
|- ...
--routes/
|- route.php
|- ...
--index.php
以这些网址为例(所有网址都应该返回/重定向404):
http://testsite.com/routes
http://testsite.com/routes/route.php
http://testsite.com/somefile.php
但是,只有资产才能直接访问(我不想包含/public/
:
http://testsite.com/assets/image.png
http://testsite.com/assets/styles/style.css
这是我到目前为止所做的:
# Make sure mod_rewrite is on
<IfModule mod_rewrite.c>
RewriteEngine on
# This should allow us to get our assets and keep them public
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.(gif|jpg|png|jpeg|css|js|swf)$ /public/$1.$2 [L,NC]
# Forward other traffic to index.php
RewriteRule ^.+$ index.php [L]
</IfModule>
我遇到的一个问题是:http://testsite.com/routes
产生:
我猜我的主要问题是在公共场合不可访问的任何内容(不确定.htacces是否可行)
答案 0 :(得分:1)
如果使用正确的规则,则无需将文件隐藏在Web根目录之上。私人文件很容易无法访问。
<IfModule mod_rewrite.c>
RewriteEngine on
# transform assets URLs to correct path, and proceed to next rule
# checking existence in RewriteConds is useless here since public URLs are not 1:1 physical paths
RewriteRule ^assets/.+ public/$0 [NS,DPI]
# send *all* URLs to index.php except those that point to an asset file that exists
RewriteCond $1 !=public/assets/ [OR]
# change the slash in next condition to your sub-directory if not serving from the web root, e.g. %{DOCUMENT_ROOT}/project/root/$0
RewriteCond %{DOCUMENT_ROOT}/$0 !-f
RewriteRule ^((?:[^/]+/){2})?.+ index.php [NS,END]
</IfModule>