在.htaccess中模拟节点/快速路由 [英] Emulating Node/Express Routes in .htaccess

查看:110
本文介绍了在.htaccess中模拟节点/快速路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试模拟nodejs/express如何使用其路由.我将所有流量转发到index.php以处理路由(使用 AltoRouter ).

I have been trying to emulate how nodejs/express work with their routes. I am forwarding all traffic to index.php to process routes (using AltoRouter).

我的文件结构是这样的:

My file struture is something like this:

-/
--public/
  |- assets
  |- ...
--routes/
  |- route.php
  |- ...
--index.php

以这些网址为例(所有网址都应返回/重定向404):

Take these urls for instance (all should return/redirect 404):

http://testsite.com/routes

http://testsite.com/routes/route.php

http://testsite.com/somefile.php

但是只能像这样直接访问资产(我不想包含/public/:

However only assets should be directly accessible like so (I dont want to include /public/:

http://testsite.com/assets/image.png

http://testsite.com/assets/styles/style.css

这是我到目前为止所拥有的:

This is what I have so far:

# 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产生:

One issue i've come accross is going: http://testsite.com/routesproduces:

我猜我的主要问题是在公共场所不应该访问的任何内容(不确定.htacces是否可行)

推荐答案

如果使用正确的规则,则不必将文件埋在Web根上方.可以很容易地使私人文件不可访问.

You don't have to bury your files above web root if you use the right rules. Private files can easily be made inaccessible.

<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>

这篇关于在.htaccess中模拟节点/快速路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆