【问题标题】:.htaccess add trailing slash if no extension before the last trailing slash.htaccess 如果在最后一个斜杠之前没有扩展名,则添加斜杠
【发布时间】:2020-10-22 09:01:08
【问题描述】:

我在这里有一个代码,它通过在末尾添加斜杠来重写 url。 条件:

  1. 无文件扩展名
  2. 末尾没有斜线

RewriteEngine On
RewriteCond %{REQUEST_URI} !\..*$
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/Brian/$1$2/ [L,R=301]

如果网址是:

http://localhost:8080/Brian/test123 -> http://localhost:8080/Brian/test123/ - CORRECT
http://localhost:8080/Brian/test123. -> http://localhost:8080/Brian/test123. - CORRECT
http://localhost:8080/Brian/test123.awd -> http://localhost:8080/Brian/test123.awd - CORRECT

http://localhost:8080/Brian/test123.awd/a -> http://localhost:8080/Brian/test123.awd/a - THIS IS MY PROBLEM

我想做出这样的结果。

http://localhost:8080/Brian/test123.awd/a/

请帮忙。谢谢!

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite


    【解决方案1】:
    RewriteCond %{REQUEST_URI} !\..*$
    

    因此,您似乎只需要查看 last 路径段,而不是 URL 路径中的 anywhere。 (顺便提一下,上面的CondPattern!\.是一样的)

    例如:

    RewriteCond %{REQUEST_URI} !\.[^/]*$
    

    [^/]* 匹配除斜线之外的任何字符到字符串的末尾,因此它只会匹配最后没有后跟斜线的路径段。


    旁白:您的.htaccess 文件似乎位于/Brian 子目录中。您可以稍微“简化”一下,避免在RewriteRule substitution 中显式声明子目录。例如:

    RewriteCond %{REQUEST_URI} !\.[^/]*$
    RewriteRule !/$ %{REQUEST_URI}/ [L,R=301]
    

    RewriteRule 模式 !/$ 只是检查请求的 URL 路径是否已经以斜杠结尾(而不是在结尾没有出现斜杠时捕获所有内容)。 REQUEST_URI 服务器变量包含完整的(相对于根的,以斜杠开头)URL 路径,我们已经确定它不以斜杠结尾。

    如果您重定向到相同的方案 + 主机名,您不一定需要将其包含在 substitution 字符串中。

    【讨论】:

    • 是的,确实是这个问题 ++
    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 2012-04-15
    • 2011-03-02
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2012-03-25
    相关资源
    最近更新 更多