【问题标题】:Multiple Rewrite Rules, Try A then B多个重写规则,尝试 A 然后 B
【发布时间】:2013-12-09 15:12:55
【问题描述】:

我的目录结构如下:

root
--/inc
--/img
--/docs
---/public
----/contact
-----/img
------telephone.jpg
-----contact.php
---/private

我的目标是使“文档”下的每个文件夹成为“包含”网页。每个文件夹都有自己的/img/ 文件夹和一个/bin/ 文件夹,其中可以包含从Mp3s 到PDF 的任何内容。

目前我正在将所有内容路由到 index.php,然后从那里手动重定向文件。但事实证明这是非常缓慢的。如果说试图通过/contact/telephone.png 访问图像,我认为会更快的是我的 .htaccess 中的类似内容:

try /img/{url_path}
Otherwise, try /docs/$1/img/$2
Otherwise route through index.php

我该怎么做呢?目前我的 .htaccess 如下:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# if file not exists
RewriteCond %{REQUEST_FILENAME} !-f
# if dir not exists
RewriteCond %{REQUEST_FILENAME} !-d
# avoid 404s of missing assets in our script
#RewriteCond %{REQUEST_URI} !^.*\.(jpe?g|png|gif|css|js)$ [NC]
RewriteRule .* index.php [QSA,L]
</IfModule>

任何帮助表示赞赏!谢谢

【问题讨论】:

    标签: .htaccess


    【解决方案1】:

    您可以在 DOCUMENT_ROOT/.htaccess 文件中执行类似操作:

    RewriteEngine On
    
    # check if this image path exists in docs/<folder>/img first
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{DOCUMENT_ROOT}/docs/$1/img/$2 -f
    RewriteRule ^([^/]+)/(.+?)/?$ /docs/$1/img/$2 [L]
    

    【讨论】:

    • 只是一个想法,但由于 /img/ 是一个实际的目录,surley 我不需要一个规则吗?
    • 另外,在 /docs/ 中有一个需要查看的 /img/ 文件夹,这似乎不在您上面的代码中?
    • 您的 URI 是否始终采用/contact/telephone.png 的形式,即/&lt;some-path&gt;/&lt;img-name&gt;
    • 是的。这行得通吗:RewriteRule ^/?([a-zA-Z_]+)/([a-zA-Z_]+)$ /docs/$1/img/$2 [L,NC,NE]
    • 确定检查更新。既然您要问try A then try B,我们需要使用条件RewriteCond %{DOCUMENT_ROOT}/docs/$1/img/$2 -f 应用某种if/elseif/elseif/else 逻辑
    猜你喜欢
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 2017-11-21
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多