【问题标题】:How can I transform a query string generated by a search form into new URL without the query string?如何将搜索表单生成的查询字符串转换为没有查询字符串的新 URL?
【发布时间】:2012-10-12 04:37:58
【问题描述】:

我有一个搜索表单,在提交时会生成类似以下网址的内容:

http://mydomain.com/index.php?find=some+text

我的目标是让它看起来像:

http://mydomain.com/find/some+text

如何使用 .htaccess 做到这一点?

到目前为止,我有这个:

RewriteCond %{REQUEST_URI}  ^/index\.php$
RewriteCond %{QUERY_STRING} &?find=(.*)&?
RewriteRule ^index.php$ find/%1? [R=301,L]

RewriteRule ^find/(.*)$ index.php?find=$1 [L]

如果查询(即我搜索的内容)仅包含数字、字母或下划线,则此方法有效,但我想让它能够搜索包括空格和其他字符在内的任何内容!

【问题讨论】:

  • 这看起来可能会让你陷入循环?

标签: php .htaccess search redirect query-string


【解决方案1】:

因此,404 错误似乎是由于 Web 服务器中的某些配置不允许 URL 具有 +(加号)造成的。 它会在第一个 + 处中断并尝试查找该名称的文件。

整理后的重写规则是这样的:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /*.index\.php\?find=([^&\.]+)?\sHTTP
RewriteRule ^/?index.php$ /find/%1? [L,R=301]
RewriteRule ^/?find/(.*)$ /index.php?find=$1 [L,NC]

感谢您的帮助!

【讨论】:

    【解决方案2】:

    不应该这样工作吗?

    RewriteRule ^find/([^/]*)$ /index.php?find=$1 [L]
    

    【讨论】:

    • 嗨!谢谢你的回复。例如,如果 query var find 有空格,它将不起作用。并且只有在我自己键入 find/sometext 或在链接中输入时才有效,并且我需要它来自表单提交。
    【解决方案3】:

    您需要匹配实际请求而不是 URI,因为 URI 会通过您的第二条规则重写。这会导致重定向循环。

    重定向浏览器:

    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?find=([^&\.]+)(&([^\ ]+))?
    RewriteRule ^/?index.php$ /find/%1?%3 [L,R=301]
    

    内部重写

    RewriteRule ^/?find/(.*)$ /index.php?find=$1 [L,QSA]
    

    【讨论】:

    • 感谢您的回复!嗯..我不知道这是否是问题,但这是有道理的。即便如此..在这个版本中,我仍然无法使用多个单词进行搜索,因为它会返回 404。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    相关资源
    最近更新 更多