【问题标题】:Vanity URLs without trailing slashes on Apache在 Apache 上没有斜杠的虚 URL
【发布时间】:2016-01-18 15:03:11
【问题描述】:

下面的代码将我们网站上 /profiles/ 目录中的所有 URL 从 example.com/profiles/name/ 重写为 example.com/name/,但我们还想删除尾部斜杠以进一步简化生成的 URL 到更漂亮的 example.com/name -- 就像在现代社交媒体上一样。

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

如何才能做到(并安全地做到)?我们在 Stumble Upon 上看到了几种解决方案,如果组合起来可能可行,但我们网站上的所有配置文件目前都有自己的物理目录,而不是通过脚本即时组装。

更新:@jon-lin 在How to access directory's index.php without a trailing slash AND not get 301 redirect 为类似情况提供了解决方案——但我们不知道如何将其应用于我们的解决方案(如上所述)。

【问题讨论】:

    标签: apache .htaccess mod-rewrite trailing-slash vanity-url


    【解决方案1】:

    你可以试试

    RewriteRule ^(.*)/+$ $1 [R=301,L]

    这适用于任何网址

    【讨论】:

    • 嘿@NooBskie!我们刚刚尝试过,但是,在 Google 的 Chrome 上对此进行了测试,example.com/name/ 重定向到包含整个内部目录结构的 URL,example.com/name 重定向到 Google 搜索。
    【解决方案2】:

    使用以下重定向:

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} /(.+)/+$
    RewriteRule ^ /%1 [R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^.*$ /profiles/$0 [NC,L]
    

    【讨论】:

    • 嘿@hjpotter92 -- 这产生了与 NooBskie 的解决方案相同的错误。
    • 谢谢!这再次重定向回 Chrome 上的 Google 搜索;在 Safari 和 Firefox 上,它会将 example.com/name 重定向回 example.com/profiles/name
    • @haadaa 您能否详细说明您的意思:“这再次重定向回 Chrome 上的 Google 搜索”?
    • 嘿@hjpotter92 当然——有了你的代码,谷歌的Chrome浏览器将example.com/name视为对example.com/name的搜索——也就是说,在组合搜索/URL栏中输入example.com/name , Chrome 会显示example.com/name 的搜索结果,而不是页面(及其错误)。我认为这是他们保护网站不显示其目录内容的方法(如果没有正确删除尾部斜杠,这确实是一种风险)。
    • 嘿@hjpotter92 由于我们所有的个人资料在example.com/profiles/name/index.html 都有自己的物理页面,是否可以使用类似于RewriteRule ^.*$ /profiles/$0/index.html [NC,L] 的内容来做到这一点?
    【解决方案3】:

    你需要禁用目录斜线

    试试:

    DirectorySlash Off
    
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /profiles/$1 [NC,L]
    

    【讨论】:

    • 嘿@Starkeen!这不起作用 - example.com/name 现在得到了“禁止 - 您无权访问此服务器上的 /profiles/name。”
    【解决方案4】:

    通过在How to access directory's index.php without a trailing slash AND not get 301 redirect 添加@jon-lin 建议的部分代码(在内部将尾部斜杠重新写入),我们实际上完成了这项工作:

    # Vanity URLs
    
    DirectorySlash Off
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ /profiles/$1 [NC,L]
    
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.*[^/])$ /$1/
    

    现在可以通过https://www.fashion.net/gucci 访问 Gucci 在 FASHION NET 上的个人资料(位于 /profiles/gucci/)——没有尾部斜线!谢谢@jon-lin!!!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2012-02-01
      • 2014-01-04
      相关资源
      最近更新 更多