如何重写特定搜索的URL?支持.htaccess/functions.php/JS实现
实现简洁搜索URL的方案
一、表单提交的JavaScript处理
给表单添加onsubmit="return submitAction(this);"后,使用以下JS代码修改跳转逻辑:
function submitAction(form) { // 获取location_name输入框(需确保输入框name属性为location_name) const locationInput = form.querySelector('input[name="location_name"]'); if (!locationInput || !locationInput.value.trim()) { return true; // 无输入时允许默认提交 } // 去除城市名称中的空格,合并为单个词 const cleanLocation = locationInput.value.trim().replace(/\s+/g, ''); // 拼接目标URL,兼容action末尾是否带斜杠的情况 const targetUrl = form.action.replace(/\/?$/, '/') + cleanLocation; // 跳转到处理后的URL window.location.href = targetUrl; // 阻止表单默认GET提交行为 return false; }
注意事项
- 若输入框
name属性不是location_name,需同步修改代码中input[name="location_name"]的对应值。
二、服务器端URL重写(必须配置,否则跳转后会出现404)
前端跳转后,服务器需要将/search/LosAngeles这类URL解析为原带参数的格式,以下提供两种实现方式:
方式1:Apache服务器使用.htaccess
在网站根目录的.htaccess文件中添加以下规则(WordPress站点需放在默认重写规则之前):
RewriteEngine On # 排除真实存在的文件或目录 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 将/search/xxx重写为/search/?location_name=xxx RewriteRule ^search/([^/]+)$ /search/?location_name=$1 [L,QSA]
方式2:WordPress站点使用functions.php
通过主题的functions.php添加重写规则,无需修改.htaccess:
// 自定义搜索重写规则 function custom_search_rewrite_rule() { add_rewrite_rule( '^search/([^/]+)/?$', 'index.php?pagename=search&location_name=$matches[1]', 'top' ); } add_action('init', 'custom_search_rewrite_rule'); // 注册查询变量,让WordPress识别location_name参数 function custom_search_query_var($vars) { $vars[] = 'location_name'; return $vars; } add_filter('query_vars', 'custom_search_query_var');
添加后需进入WordPress后台设置→固定链接,点击「保存更改」以刷新重写规则。
内容的提问来源于stack exchange,提问作者Kiki
相关产品推荐
相关产品推荐

