Remove Query Strings from Static Resources

Home » Content Management Systems » Remove Query Strings from Static Resources
November 8, 2016 Content Management Systems, Wordpress No Comments

One of the most important factors in optimizing your website’s performance is represented by the removal of the query strings from the static resources.

The query string represents a method with which both plugins and themes pass on content values and/or carry version details when the page is executed in the browser. The query strings are used both with Javascript and CSS and they were implemented by developers in order to instantly render new updates.

While being helpful both for developing and troubleshooting, the use of query strings on production sites is a bad idea as it slows down the site.

I’ve provided below a series of methods to resolve the latency resulted from the use of query strings in the code:

1. The .htaccess method:

If you’re using WordPress and you have a heavy site then removing the query strings from static resources is not only a good idea, but also a must and you can do that by adding the code below in your .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{QUERY_STRING} !=""
RewriteCond %{QUERY_STRING} !^p=.*
RewriteCond %{QUERY_STRING} !^s=.*
RewriteCond %{REQUEST_URI} !^/wp-admin.*
RewriteRule ^(.*)$ /$1? [R=301,L]

The code above uses mod_rewrite to determine if the query strings are executed on the frontend and eliminates them if the rule matches, but still allows them via the WordPress backend where they might be still needed.

2. The WordPress plugin method:

Another method to disable query strings on your WordPress site is using the Remove Query Strings plugin, which although seems easier than the .htaccess method referenced above is given as a second recommendation simply because the plugin has a few negative reviews on the WordPress repository and doesn’t actually receive constant updates from it’s developer.

3. The theme alteration method:

Probably the most complicated way of disabling the query strings from static resources assumes altering the theme and this is due to two reasons:

  • He who will alter the theme requires a little bit of coding understanding and experience;
  • Such an alteration must be made on a child theme as altering the main theme could cause the code to be overwritten upon the next update.

However, if you know what you’re doing then you can disable the query strings by adding this code at the bottom of your functions.php file:

// Remove query string from static files
function remove_cssjs_ver( $src ) {
 if( strpos( $src, '?ver=' ) )
 $src = remove_query_arg( 'ver', $src );
 return $src;
add_filter( 'style_loader_src', 'remove_cssjs_ver', 10, 2 );
add_filter( 'script_loader_src', 'remove_cssjs_ver', 10, 2 );

That’s about it, I hope this helps.