首页 > 解决方案 > GET-Request 中的斜杠 (/) 和 htaccess 中的 mod_rewrite 语句

问题描述

我对这个话题有点疯狂,希望能找到一些帮助。

我目前正在将我的网站重建为 MVC 结构。这还包括对 SEO 友好(漂亮)的 URL。

我已经实现了我的 URL 请求的转换

from: http://www.example.com/company?id=about_us
  to: http://www.example.com/company/about_us 

我的 .htaccess 文件

RewriteEngine On
RewriteBase /

# Transforms an ugly-URL into a pretty-URL ('external redirect' updates also adress in browser)
#    ugly URL: www.example.com/company?id=about_us
#  pretty URL: www.example.com/company/about_us

RewriteCond %{QUERY_STRING} ^id=([\w-]+)$
RewriteRule ^(.+)$ $1/%1? [R=301,L]

# Transform an pretty-URL into a ugly-URL ('internal redirect')
#  pretty URL: www.example.com/company/about_us
#    ugly URL: www.example.com/index.php?url=company/about_us

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

现在游戏中出现了 FORM 的 GET-Request(某些文章的选择框),它不适用于上述 htaccess 文件。而每篇文章都有一个 SEO_slug 保存在数据库中,它是动态放入表单中的。SEO-slug 已经有这种格式:

"<city>/<type>/<articlename>"

HTML 如下所示:

<form method='get' action='../articles/'>
  <select name='id'>
     <option value='london/fruit/article_1' >Article 1</option>
     <option value='london/nuts/article_2'  >Article 2</option>
     <option value='newyork/fruit/article_3'>Article 3</option>
     <option value='newyork/nuts/article_4' >Article 4</option>
     <option value='miami/fruits/article_5' >Article 5</option>
  </select>
</form>

问题:

现在,请求被发送到服务器,但斜杠 (/) 被转换为“%2f”,这会在我当前的 htaccess 中生成服务器内部错误。

问题

1) 我可以阻止从斜杠 (/) 到 '%2f' 的转换吗?

2)我如何更新我的 mod_rewrite 才能启用它。我看过这么多网站,但我从来没有找到一个好的解决方案。我能够做到这一点:

RewriteCond %{QUERY_STRING} ^id=([\w-]+)(%2F*)(.*)(%2F*)(.*)$
RewriteRule ^(.+)$ $1/%1/%3/%5? [R=301,L]

,但我对斜线的数量有疑问,因为有时深度不同。

有人可以给我一个好的建议吗?非常感谢!也许我试图以错误的方式解决这个故事,需要完全不同的想法??

干杯蒂姆

标签: .htaccessmod-rewritegetseo

解决方案


Finallay我找到了一个解决方案,想和大家分享一下:

RewriteEngine On
RewriteBase /

# Transforms an ugly-URL into a pretty-URL ('external redirect' updates also adress in browser)
#    ugly URL: www.example.com/company?id=about_us
#  pretty URL: www.example.com/company/about_us
#
# REMARK: The important group is the thrid. The two first groups are
#         important if the query string contains slahes (/) that are
#         encoded as '%2F'. As there is no 'replace'-function each
#         Level of '%2F' needs to be rewritten step by step

RewriteCond %{QUERY_STRING} ^id=([\w-]+)%2F([\w-]+)%2F([\w-]+)$
RewriteRule ^(.+)$ $1/%1/%2/%3? [R=301,L]

RewriteCond %{QUERY_STRING} ^id=([\w-]+)%2F([\w-]+)$
RewriteRule ^(.+)$ $1/%1/%2? [R=301,L]

RewriteCond %{QUERY_STRING} ^id=([\w-]+)$
RewriteRule ^(.+)$ $1/%1? [R=301,L]

# Transform an pretty-URL into a ugly-URL ('internal redirect')
#  pretty URL: www.example.com/company/about_us
#    ugly URL: www.example.com/index.php?url=company/about_us

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

如果您对此有任何意见以改进它,我很高兴听到它。


推荐阅读