>  기사  >  백엔드 개발  >  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으로 문의하세요.