【问题标题】:.htaccess redirect & beautify query string.htaccess 重定向和美化查询字符串
【发布时间】:2023-03-20 05:25:01
【问题描述】:

这是我想要实现的目标:

浏览器请求:example.com/webApp/controller/action/?param1=param1value

  • URL 的静态(始终相同)部分是webApp/
  • URL 的动态部分是controller/action/?param1=param1value。通常它由REQUEST_URI(由不同数量的部分组成的路径)和QUERY_STRING组成,它可以是任何东西,例如:
    • site/index/?page=2
    • books/index/?page=2&sort=name
    • users/list
    • foo/bar
    • user/profile/posts/?page=2
  • 上面列出的 URL 在 .htaccess(服务器接收的内容)之后应如下所示:
    • index.php?path=site/index/page/2
    • index.php?path=books/index/page/2/sort/name
    • index.php?path=users/list
    • index.php?path=foo/bar
    • index.php?path=user/profile/posts/page/2
  • 当用户在浏览器中看到没有 index.php 部分的 URL 时:
    • site/index/page/2
    • books/index/page/2/sort/name
    • users/list
    • foo/bar
    • user/profile/posts/page/2

基本上,我想通过将所有?& 字符替换为/ 并将其动态附加到REQUEST_URI 来清理URL 的QUERY_STRING 部分。

我一直在做很多关于这个主题的搜索。不幸的是,最接近的匹配是硬编码 QUERY_STRING 参数转换为路径的示例。相反,我想将所有 QUERY_STRING 部分(如果有的话)动态地转换为路径。

我目前的.htaccess文件内容如下:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI}  !(\.png|\.jpg|\.gif|\.jpeg|\.bmp|\.css|\.js)$
RewriteRule ^([^?]*)$ index.php?path=$1 [NC,L,QSA]

唯一缺少的部分是清理QUERY_STRING,如上所述。此外,如果请求 URI 是上面代码中列出的文件(扩展名列表),则不会通过 index.php 处理。

【问题讨论】:

    标签: .htaccess redirect mod-rewrite clean-urls


    【解决方案1】:

    我已通过使用以下 .htaccess 代码部分解决了该问题:

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI}  !(\.png|\.jpg|\.gif|\.jpeg|\.bmp|\.css|\.js)$
    
    RewriteCond %{QUERY_STRING} ^(.*)=(.*) [OR]
    RewriteRule ^([^?]*)$ index.php?path=$1&%1=%2 [NC,L]
    
    • QUERY_STRING 不再附加在 URL 的末尾(QSARewriteRule 中删除)。
    • 相反,QUERY_STRING 与条件 RewriteCond %{QUERY_STRING} ^(.*)=(.*) [OR] 匹配,随后通过在 RewriteRule 中包含标记 %1%2 来使用。
    • 此解决方案不会从 URL 中删除 GET 参数,但它确实确保它们不会出现在 path 参数中。
      • 相反,查询字符串正常工作并创建自己的GET参数条目(因为它现在以&而不是?开头。?已用于参数path
      • 第一篇文章中描述的情况导致查询字符串格式错误,因为“第一个参数字符?”被使用了两次。至少这是我的假设..

    【讨论】:

      猜你喜欢
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 2010-11-06
      • 2014-05-10
      相关资源
      最近更新 更多