【问题标题】:mod_rewrite - Only use whatever is after the last forward slashmod_rewrite - 仅使用最后一个正斜杠之后的内容
【发布时间】:2023-03-11 08:43:01
【问题描述】:

所以我已经配置了我的 .htaccess 文件,这样当我加载网页 (http://example.com/about) 时,它会透明地将其重定向到 http://example.com/about.html,但是,我希望它现在是能够做到(http://example.com/about/contact),然后让它透明地重定向到http://example.com/about/contact.html。我想理想情况下它会完全忽略 URL 的“/about/”部分,只使用联系人部分。

这是我现在正在使用的:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite


    【解决方案1】:

    使用这个:

    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-d
    
    # folder/file => folder/file.html
    RewriteRule ^([a-z0-9_\-]+)/([a-z0-9_\-]+)/?$ $2.html [NC,L]
    
    # file => file.html
    RewriteRule ^([a-z0-9_\-]+)/?$ $1.html [NC,L]
    

    【讨论】:

    • 这几乎可以工作,但问题是所有文件都位于根目录中,因此 contact.html 不在 /about/ 目录中。所以当我去example.com/about/contact时,它应该从根目录加载contact.html
    • 哦,我明白了,我更新了答案 - 这将影响所有子文件夹。如果您有确实存在的子文件夹,则需要指定它们
    • 太棒了,这行得通。我有一个名为“i”的子目录,我将如何在 .htaccess 中声明它?谢谢
    • 是的,你可以。或者您创建一个规则,如果请求是“/i/...”,则忽略该规则
    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多