【问题标题】:.htaccess add trailing slash on pages except when #'s are in the URL.htaccess 在页面上添加尾部斜杠,除非 # 在 URL 中
【发布时间】:2012-06-20 20:20:43
【问题描述】:

我希望我的网址添加尾部斜杠,但前提是网址不以锚结尾。

这是我当前的 .htaccess 文件

# ----------------------------------------------------------------------
# Enable Rewrite Engine
# ----------------------------------------------------------------------

RewriteEngine On
RewriteBase /


# ----------------------------------------------------------------------
# Remove the www from the URL
# ----------------------------------------------------------------------

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]


# ----------------------------------------------------------------------
# Add a trailing slash to paths without an extension
# ----------------------------------------------------------------------

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule ^(.*)$ $1/ [L,R=301]


# ----------------------------------------------------------------------
# Remove index.php
# ----------------------------------------------------------------------

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L] 


当我链接到锚定部分时,URL 会被写入:

http://mysite.com/subdir/#anchor


什么时候应该是这样的:

http://mysite.com/subdir#anchor


常规 URL 应如下所示:

http://mysite.com/directory/sub/



我很困惑,所以任何帮助都会很棒!

干杯,

【问题讨论】:

    标签: apache .htaccess mod-rewrite expressionengine


    【解决方案1】:

    你看过 Apache 的 Directory Slash 设置吗?

    这是我们在 .htaccess 中用来处理类似问题的方法

    DirectorySlash Off
    DirectoryIndex index.php index.html index.htm
    

    【讨论】:

    • 似乎没有成功,不过请记住这一点以备将来使用
    【解决方案2】:

    不要认为问题在于您的重写规则。片段(URI 末尾的#something)永远不会被发送到服务器,它们被用作浏览器正在呈现的页面内的从属资源。

    确保您所提供的 HTML 中的锚点中不包含尾部斜杠,或者您没有将它们附加到浏览器端的 javascript。


    编辑:

    好吧,如果要删除 URI 末尾添加的斜杠,您可能需要注释掉这条规则:

    # ----------------------------------------------------------------------
    # Add a trailing slash to paths without an extension
    # ----------------------------------------------------------------------
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
    RewriteRule ^(.*)$ $1/ [L,R=301]
    

    【讨论】:

    • 啊,对,在 URI 的最末端没有添加斜杠(我更新了我的帖子)。但是,斜线仍然添加在 # 符号之前。
    • 我的错,我再次更新了我的帖子,说我希望我的 URL 添加斜杠,但前提是 URL 不以 # 结尾
    • @Dan 你不能这样做,至少不能使用 htaccess 和 mod_rewrite。 Apache 不知道 URL 何时以“#”结尾。 URI 片段仅限于浏览器。
    • 对我来说就像一个魅力。谢谢@JonLin!
    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2012-04-15
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多