大网数据广告活动
网站运营与故障问答

How do I redirect /search/ to /?s=

· 52CE 我爱测

I have a typical Wordpress site, with a typical Search page set up which uses the typical GET format <form id="searchform" action="http://example.com" method="get"> <input id="s" type="text" name="s" placeholder="Search Again"> <…

问题原文

原帖链接 · jchwebdev · CC BY-SA 3.0

I have a typical Wordpress site, with a typical Search page set up which uses the typical GET format

    <form id="searchform" action="http://example.com" method="get">
        <input id="s" type="text" name="s" placeholder="Search Again">
    </form>

For users' convenience, I'd like to have the following url redirect to the search page:

http://example.com/search?search-term

Redirect to:

http://example.com/search/search-term

How do I do this?

I need this to work even if the user enters no search parameter. In other words, if the user enters:

http://example.com/search/

...the displayed URL should remain

http://example.com/search/

Not the typical

http://example.com/?s=

...even though the page is still redirecting to the Wordpress search template.

Hope that made sense.

UPDATE: The closest I've been able to get is this:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

   # redirect /search/param to /?s=param
   RewriteCond %{QUERY_STRING} (.*)
   RewriteRule ^search/?$ /?s=%1 [R=302,L]  

   #standard wordpress stuff    
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>   

已采纳解答

原帖链接 · MrWhite · CC BY-SA 3.0

In order to match against the query string (everything after the first ?) you need to use a RewriteCond directive and check against the QUERY_STRING server variable. The RewriteRule pattern only matches against the URL-path.

So, try something like the following in .htaccess, before any WordPress rewrites:

RewriteCond %{QUERY_STRING} (.*)
RewriteRule ^search/?$ /?s=%1 [R=302,L]

If the user requests /search?[something] then they are redirected. Where [something] is entirely optional.

This is a temporary (302) redirect, change to a permanent (301) when you are sure it's working OK.


UPDATE: Instead of using the query string to pass the search term (ie. /search?search-term, use the URL-path instead (ie. /search/search-term). And keep the original URL in the browser (ie. don't externally redirect to /?s=) then try something like the following instead:

RewriteRule ^search(/(.*))? index.php?s=$2 [L]

(This replaces both the directives above.)

This allows you to specify either /search, /search/ or /search/search-term and the URL stays in the browsers address bar.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2016-03-03)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。