【问题标题】:RewriteRule add query if directory exists如果目录存在,RewriteRule 添加查询
【发布时间】:2015-08-04 01:36:57
【问题描述】:

假设

将所有内容重定向到 index.php,除了 Images 文件夹(如果文件存在)。 例如:

/main/test => index.php?controller=main&action=test

/image/exists.png => image/exists.png

/image/another.png => index?controller=image&action=another.png

当前代码

<IfModule mod_rewrite.c>
    RewriteEngine On
    Options +FollowSymlinks

    RewriteCond "%{REQUEST_FILENAME}" "!-f"
    RewriteRule ^image/(.*)$ index.php?controller=$1&action=$2 [NC,L]

    RewriteRule ^(.*)/(.*)/(.*)/(.*)/.*$ index.php?controller=$1&action=$2&v1=$3&v2=$4 [NC,L]
    RewriteRule ^(.*)/(.*)/(.*)/(.*)/$ index.php?controller=$1&action=$2&v1=$3&v2=$4 [NC,L]
    RewriteRule ^(.*)/(.*)/(.*)/(.*)$ index.php?controller=$1&action=$2&v1=$3&v2=$4 [NC,L]
    RewriteRule ^(.*)/(.*)/(.*)/$ index.php?controller=$1&action=$2&v1=$3 [NC,L]
    RewriteRule ^(.*)/(.*)/(.*)$ index.php?controller=$1&action=$2&v1=$3 [NC,L]
    RewriteRule ^(.*)/(.*)/$ index.php?controller=$1&action=$2 [NC,L]
    RewriteRule ^(.*)/(.*)$ index.php?controller=$1&action=$2 [NC,L]
    RewriteRule ^(.*)/$ index.php?controller=$1 [NC,L]
    RewriteRule ^(.*)$ index.php?controller=$1 [NC,L]
</IfModule>

不良反应及请帮忙的原因

如果我将路径放入现有文件夹,您将被重定向到一个非常奇怪的路径。例如,如果我在浏览器中编写类似 localhost/image 的 URL,我会得到类似 localhost/image/?controller=Image 的 URL。最后 - 它加载了一个很好的文件,但看起来很丑。

/image => index.php?controller=image(但在浏览器的 URL 字段中:/image/?controller=Image

PS 如果我使用 Firefox,我可以在没有 Query 的情况下获得很好的 URI。我认为这是因为 Firefox 在 URL 末尾添加了一个斜杠而没有扩展名。

如何“修复”它?

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    您的第一个问题是所有那些 (.*) 因为它们是贪婪的,所以 REGEXP 中的第一个将消耗所有字符,直到行尾。如果您只想要一个消耗到下一个 / 的 REGEXP,请使用 ([^/]*)([^/]+) .

    接下来要排除您想要使用SKIP 指令的真实文件,例如。在规则集的顶部粘贴以下内容:

    # Skip the next 10 RewriteRule is the requested file physically exists, in the image
    # directory
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^image/ - [S=10]
    

    【讨论】:

    • 顺便说一句,“L”在模式匹配的情况下不会导致跳过?
    • 以不同的方式。 L 在重定向发生后生效。
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2016-04-04
    • 1970-01-01
    • 2021-12-13
    • 2011-02-16
    • 2023-04-09
    相关资源
    最近更新 更多