首頁  >  文章  >  後端開發  >  php如何改写搜索时url

php如何改写搜索时url

WBOY
WBOY原創
2016-06-06 20:25:061139瀏覽

比如:
http://segmentfault.com/search?q=hello

我想实现:
http://segmentfault.com/search/hello

这种URL。

搜索表单用的'GET'URL后面会 ?、& 什么的。

使用Rewrite可以直接搜索http://segmentfault.com/search/hello这样的链接。

但是在搜索表单搜索时URL却还是出现带 ?、& 这样的符号。

导致URL好难看。

请问各位有什么办法可以改写?

回复内容:

比如:
http://segmentfault.com/search?q=hello

我想实现:
http://segmentfault.com/search/hello

这种URL。

搜索表单用的'GET'URL后面会 ?、& 什么的。

使用Rewrite可以直接搜索http://segmentfault.com/search/hello这样的链接。

但是在搜索表单搜索时URL却还是出现带 ?、& 这样的符号。

导致URL好难看。

请问各位有什么办法可以改写?

用 JS 绑定 表单的 submit 事件,然后在表单提交的时候,用 location.href 来跳.
类似于下面这样:

<code>    <form action="/search" method="GET" onsubmit="return rewrite(this);">
        <input type="text" name="content" id="content">
        <input type="submit">
    </form>
    <script type="text/javascript">
    function rewrite(form){
        location.href = form.action + '/' + document.getElementById('content').value;
        return false;//阻止表单跳转
    }
    </script></code>

目前是直接将事件写在 FORM 标签里的, 以后可以将绑定事件的做为了个公用的JS, 在各各页面上加载上.
然后JS自动将搜索的这个表单做这样的处理.

或者就是在服务器上配置 Rewrite 将 表单提交时产生的那个URL(/search?x=xxx)重写为 /search/xxx.
这样的好处是不需要在页面上加JS代码, 坏处是会多一个301/302跳转.

Rewrite On
RewriteRule ^search?q=(.*)$ /search/index.php?keyboard=$1

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn