【问题标题】:RewriteRule for first directory in URL only仅 URL 中第一个目录的 RewriteRule
【发布时间】:2013-09-19 19:49:46
【问题描述】:

如果不重定向所有对 .css 和 .js 文件的请求,我不知道如何表述这个 RewriteRule。

我需要

domain.com/randomfolder/

为请求的任何文件夹转到我的域的索引(即 domain.com/index.php),但保持 url 完整。

这似乎很容易,但我似乎无法指定我只希望重定向目录的第一个实例。

例如:

重写规则 ^(.*)$ index.php

可以重定向,但是当我的 index.php 调用 /css/main.css 时,它会返回 index.php。

有没有办法说 domain.com/subdirectory/ 应该重定向但 domain.com/subdirectory/file.css 不应该?

我可以排除 /css/ 和 /js/ 目录,但我不知道怎么做。

【问题讨论】:

  • 所以我们需要深入了解您真正想要的东西。您是否尝试将不指向目录结构中实际文件和/或文件夹的请求重定向到 index.php?这是实现诸如此类的前端控制器的典型方式。如果不是,您真的想将除请求之外的所有内容重定向到 *.css 和 *.js 文件吗?图片(如果有的话)呢?

标签: regex apache mod-rewrite


【解决方案1】:
RewriteRule ^([^/]+)/?$ /index.php?folder=$1 [L]

这会将www.example.com/subdirectory/ 重定向到www.example.com/index.php?folder=subdirectory,而不会更改访问者看到的URL。它不会重定向对子目录中任何特定文件的请求,也不会重定向对子目录中子目录的请求。

URL Requested:                Redirect:
--------------------------------------------------------------------
example.com/css               example.com/index.php?folder=css
example.com/css/              example.com/index.php?folder=css
example.com/css/main.css      example.com/css/main.css (no redirect)
example.com/css/js/           example.com/css/js/      (no redirect)

【讨论】:

  • 谢谢!我必须在样式表 href 中添加一个额外的斜线,然后它才能工作。 (href="css/main.css" > href="/css/main.css")
【解决方案2】:

这应该适合你:

<Files ~ "\.(css|js)$">
    RewriteRule ^subdirectory(.*)$ index.php
</Files>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2014-01-29
    • 1970-01-01
    • 2014-06-29
    • 2014-06-22
    相关资源
    最近更新 更多