【问题标题】:.htaccess to redirect parts of a URL to local files.htaccess 将部分 URL 重定向到本地文件
【发布时间】:2013-09-27 17:55:29
【问题描述】:

我有一个自定义网络应用程序,文件结构如下:

/apps/calendar/frontend/index.php
/apps/calendar/frontend/view/index.php
/apps/calendar/backend/index.php
/apps/calendar/backend/edit/index.php
/apps/calendar/backend/add/index.php
/apps/calendar/backend/view/index.php

我正在尝试编写一个 .htaccess 文件来帮助重定向文件,这样他们就看不到“真实”路径。

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/admin
RewriteRule ^([^/\.]+)/(.*)/(.*)($|/$) /apps/$1/frontend/$2/$3 [NC,L]
RewriteRule ^([^/\.]+)/(.*)($|/$) /apps/$1/frontend/$2 [NC,L]
RewriteRule ^([^/\.]+)($|/$) /apps/$1/frontend/ [NC,L]

当我访问 localhost/calendar 时,它应该将重定向映射到 /apps/calendar/frontend/index.php。但是当我访问 localhost/calendar/add 时,它会给我一个 301(永久移动),然后在控制台中显示 localhost/apps/calendar/frontend/add/index.php 的完整页面。任何人都知道为什么会发生这种情况?或者有更好的方法来解决这个问题?这些应用程序可能有大量的子目录,所以我并不是特别热衷于为永远的子目录组合制定规则。

你也可以看到我有一个 /admin 路径,它将加载应用程序的 /backend/ 部分。我会假设我可以用 /admin 的前缀做类似的代码?

【问题讨论】:

    标签: php apache .htaccess mod-rewrite redirect


    【解决方案1】:

    您可能也对这个问题感兴趣:Create blog post links similar to a folder structure.

    鉴于您的 .htaccess 位于您的域 /home/youraccount/public_html/.htaccess 的根文件夹中,它看起来像这样:

    Options +FollowSymLinks -MultiViews
    
    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{REQUEST_URI} !^/(admin|apps) [NC]
    RewriteCond %{DOCUMENT_ROOT}/apps/$1 -d
    RewriteRule ^([^/]+)/?(|.*)$ /apps/$1/frontend/$2 [NC,L]
    
    RewriteCond %{REQUEST_URI} !^/apps [NC]
    RewriteCond %{DOCUMENT_ROOT}/apps/$1 -d
    RewriteRule ^admin/([^/]+)/?(|.*)$ /apps/$1/backend/$2 [NC,L]
    

    假设用户访问:

    http://domain.com/calendar
    http://domain.com/calendar/
    http://domain.com/calendar/add
    

    以上所有内容都会重定向到

    /apps/calendar/frontend/index.php
    /apps/calendar/frontend/index.php/
    /apps/calendar/frontend/index.php/add
    

    如果用户访问:

    http://domain.com/calendar/admin
    http://domain.com/calendar/admin/
    http://domain.com/calendar/admin/add
    

    它会去:

    /apps/calendar/backend/index.php
    /apps/calendar/backend/index.php/
    /apps/calendar/backend/index.php/add
    

    因此它将使 index.php 成为您的每一端的控制器:

    /apps/calendar/frontend/index.php
    /apps/calendar/backend/index.php
    

    【讨论】:

    • 谢谢.. 只是一些调整以适应我的应用程序结构。 /frontend 将由公共用户直接加载。当 /backend 文件通过 AJAX 加载时,使用 /admin 页面内的 $.load()。所以应该是/admin/apps/calendar/index.php; /admin/apps/日历/添加
    • 对不起,我怎样才能让 /index.php 加载?添加: RewriteCond %{REQUEST_URI} !^index.php [NC] 条件对我不起作用。有什么想法吗?
    • /admin/apps/calendar/ 但可以从http://domain.com/admin/calendar 访问?在当前设置下,index.php 仅在您将其附加到 HTML 上的 URL 时才会显示。
    • 不错!是否可以不在 /apps/calendar/frontend/index.php 中使用控制器?所以如果它是 /calendar/add 它只会重定向到 /apps/calendar/frontend/add/index.php ?
    • 只是一个想法,但请尝试更新,看看是否能如您所愿。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多