【问题标题】:URL Rewrite to exclude existing directoriesURL 重写以排除现有目录
【发布时间】:2009-08-20 21:56:40
【问题描述】:

我正在尝试将 URL 从 example.net/customnameexample.net/customname/ 重定向到 example.net/my/home.php?username=customname 。这本身并不复杂:

RewriteRule ^([a-zA-Z0-9_-]+)$ my/home.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ my/home.php?username=$1

但是,我想排除我现有的目录和文件,例如 example.net/about/example.net/files。我不太清楚如何使用 RewriteCond(我需要多个重写条件吗?)以排除像 example.net/about/ 这样的项目被重写为 example.net/home.php?username=about。我该怎么做?

谢谢!

编辑:这是确切的解决方案...

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([a-zA-Z0-9_-]+)/?$ my/home.php?url=$1 [NC,L]

【问题讨论】:

  • 关于您的编辑:为什么您使用两组完全独立的规则,其唯一区别是单个字符?它冗长且效率低下,所以我建议使用选项限定符(问号)作为 localshred,我在我们的答案中也这样做了。
  • 很对,我把答案改成了reflect。

标签: regex apache mod-rewrite url-rewriting


【解决方案1】:

RewriteCond 有一些特殊的模式正是为了这个目的。试试这个:

RewriteCond %REQUEST_FILENAME ! -d
RewriteCond %REQUEST_FILENAME ! -f
RewriteRule ^([a-zA-Z0-9_-]+)/?$ my/home.php?username=$1

【讨论】:

  • 我以前见过 -d 和 -f ,但没有意识到他们是这样做的。谢谢!我在上面发布了我完整的语法正确解决方案。
【解决方案2】:

可以使用RewriteCond(重写条件),类似这样:

RewriteCond %{REQUEST_URI} ! ^\/(about|files)\/?$
RewriteRule ^([a-zA-Z0-9_-]+)/?$ my/home.php?username=$1 [L]

这只会在规则通过上面的所有条件时才有效地应用规则,类似于使用 if 语句。

http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 2020-01-09
    相关资源
    最近更新 更多