【问题标题】:URL Rewriting and Redirecting with folders使用文件夹的 URL 重写和重定向
【发布时间】:2012-11-11 08:29:53
【问题描述】:

我知道有很多关于 htaccess 的问题,但我尝试了可以​​在 Google 和 StackOverFlow 上找到的不同代码,但都没有奏效。

我的根目录中有以下内容:

index.php
.htaccess (the one I am trying to write)
controllers
    --index.php
    --mycontroller.php
models
    --mymodel.php
view
    -index.php
    --myview.php

(我正在使用 MAMP&Firefox 在本地主机上工作)

我拥有的是这个链接

localhost:8888/MySite/controllers/mycontroller.php

我想要的是

localhost:8888/MySite/mycontroller

当我手动输入 url 时,我希望它在我的 MVC 代码中被重定向到正确的控制器

我试过了:

RewriteEngine On
RewriteBase /
RewriteRule ^/(.*)$ /controllers/$1 [L]

当我转到 blabla/controllers/mycontroller.php 时它不会重定向,并且当我手动转到 blabla/mycontroller 时不明白我在问什么。

【问题讨论】:

    标签: apache .htaccess redirect url-rewriting


    【解决方案1】:

    如果你的基地在/MySite/,那么它需要反映RewriteBase

    RewriteEngine On
    RewriteBase /MySite/
    
    # match against the php filename
    RewriteCond %{REQUEST_URI} ^/Mysite/(.*)$
    
    # check to see if the request, routed through controllers actually points to an existing file
    RewriteCond %{DOCUMENT_ROOT}/MySite/controllers/%1.php -f
    
    # rewrite
    RewriteRule ^(.*)$ controllers/$1.php [L]
    

    这应该接受对 URI 的请求:/MySite/foo 并将其重写为 /MySite/controllers/foo.php如果控制器目录中有 foo.php 文件

    【讨论】:

    • 我尝试了您的代码并请求了 /MySite/foo,但它不起作用(我的控制器中有一个 foo 文件)。当我执行 /MySite/controllers/foo 时,它可以工作(当然),但不会重写为 /MySite/foo ... 可以关闭什么?顺便说一句,我怎样才能看到我的 .htaccess 是否真的被通读而不是忽略?
    • @BabyAzerty 您可以尝试添加RewriteRule ^ http://google.com/ [L,R] 以查看是否有任何请求发送至谷歌。编辑了我的答案,意识到您需要从%{REQUEST_URI} 中拉出最后一个路径节点。
    【解决方案2】:

    这样做是为了让它工作:

    RewriteEngine On
    RewriteBase /MySite/
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    
    RewriteRule ^.*$ controllers/$0.php [L]
    

    【讨论】:

      猜你喜欢
      • 2014-02-19
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 2013-10-16
      • 2013-10-08
      • 1970-01-01
      相关资源
      最近更新 更多