How to change the default search URL slug in WordPress

While WordPress can be configured to display posts and pages with SEO-friendly URLs, the platform’s default search URL structure (https://www.mydomain.com/?s=search-term) is less attractive for search engine crawlers.

However, with a few simple tweaks, you can amend the search URL to be more consistent with your site’s permalinks format, optimising search pages for search engines.

Amend Your Site’s Functions File

The easiest way to change your search page slug is to edit your site’s functions.php file. You can download the file using an FTP client, then edit the file locally using a text editor or simple use cPanel File Manager in the HostPapa Dashboard to edit the file directly on the server.

Head to your WordPress site root, then select app > themes.  Open the directory pertaining to your active WordPress theme.

cPanel File Manager

Copy and paste the following code at the bottom of the functions.php file:

/**
* Change search page slug.
*/

function wp_change_search_url() {
    if ( is_search() && ! empty( $_GET['s'] ) ) {
        wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) );
        exit();
    }  
}
add_action( 'template_redirect', 'wp_change_search_url' );

 

functions.php

Save the file (and upload to the server, if required), then head to your site’s front-end and use your search feature. Notice how the URL structure has changed to https://www.mydomain.com/search/search-term.

Change Search URL Slug Using .htaccess

The alternative method to change your search URL slug is to use a .htaccess rule. .htaccess is a configuration file used by the Apache web server and can be used to rewrite the format of URLs.

The .htaccess file can be found in your WordPress root folder. Download with an FTP client and edit with a text editor application, or use cPanel File Manager once again to edit the file directly on the server.

cPanel File Manager

Add the following code to the .htaccess file:

# Change WordPress search URL slug
RewriteCond %{QUERY_STRING} \\?s=([^&]+) [NC]
RewriteRule ^$ /search/%1/? [NC,R,L]

.htaccess

Save the file (and upload to the server, if required), then head to your site’s front-end and use your search feature. Notice again how the URL structure has changed.

If you notice any problems or if you need any help, please open a new support ticket from your HostPapa Dashboard. More details on how to open a support ticket can be found here.

Related Articles

Get online with our affordable web hosting

Get online with our affordable web hosting

Learn more now
HostPapa Mustache