【问题标题】:How can I do to limit a RewriteRule only for the current directory with .htaccess?如何使用 .htaccess 仅针对当前目录限制 RewriteRule?
【发布时间】:2018-09-15 17:25:01
【问题描述】:

假设我们正在谈论website.com,并且在根目录中有一个名为tags 的文件夹。

这个目录帮助我拥有“动态网址”,例如:website.com/tags/my-dinamic-urlwebsite.com/tags/another-example

为此,经过一整天的搜索 :) 我发现可以使用 .htaccess 来实现,目前它看起来像这样:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule (.*) index.php?t=$1 [QSA]

从我的小角度来看,这太棒了,对某些人来说可能很有趣,但在 stackoverflow.com 上搜索了几个小时后,我终于了解了一些关于 .htaccess 文件和 RewriteRule 的内容。

问题是:现在,这个 RewriteRule 会无休止地继续下去,因为如果我尝试像 website.com/tags/my-dinamic-url/continue/another-continue/endlessly 这样的东西,它会继续下去,而不是仅仅限制在 website.com/tags/my-dinamic-url

我该怎么做才能阻止它?我需要,如果有人添加斜线,页面需要返回 404 错误。

所以website.com/tags/my-dinamic-url 需要工作但website.com/tags/my-dinamic-url/website.com/tags/my-dinamic-url/something 需要返回404 错误。

【问题讨论】:

    标签: html .htaccess mod-rewrite


    【解决方案1】:

    可以通过检查 uri 是否以 /tags 开头来防止无限重定向。假设重写规则仅在 uri 为一级深时适用:

    # pass if the uri not starting with /tags/*
    RewriteCond %{REQUEST_URI} !^/tags/ [NC]
    
    # redirect, ([^/]+) matches any characters, except / character (slash)
    RewriteRule ^([^/]+)$ /tags/$1 [R,QSA,L]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多