Heim  >  Artikel  >  Backend-Entwicklung  >  php如何改写搜索时url

php如何改写搜索时url

WBOY
WBOYOriginal
2016-06-06 20:25:061139Durchsuche

比如:
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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn