【问题标题】:Emulating Node/Express Routes in .htaccess在 .htaccess 中模拟节点/快速路由
【发布时间】:2016-11-05 20:27:17
【问题描述】:

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

我的文件结构是这样的:

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

以这些 url 为例(都应该返回/重定向 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/routesproduces:

我想我的主要问题是任何不公开的东西都不能访问(不确定 .htacces 是否可行)

【问题讨论】:

  • 在大多数情况下,适当的框架会让您将 .htaccess 和 index.php 文件移动到 /public 文件夹,然后将域的 webroot 映射到 /public。这样,您的路由文件夹 - 以及任何其他可以与您的后端逻辑相关联的东西 - 都不会出现在 webroot 之外,并且目录遍历无法访问。
  • @maiorano84 如果我无法访问您的主机配置,我可以不自己映射吗?
  • 嗯,如果您没有服务器访问 Apache/NGINX 配置的权限,事情就会变得复杂。您是否有权访问 cPanel 或 Plesk 等服务器控制面板?
  • @maiorano84 我愿意。
  • @maiorano84 我不能只将所有流量(除了到公共文件夹中的特定文件之外)转发到 index.php 吗?

标签: php .htaccess mod-rewrite altorouter


【解决方案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>

【讨论】:

    猜你喜欢
    • 2014-11-19
    • 2020-03-27
    • 2014-02-03
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多