A clean and SEO-friendly URL or web hyperlink address is important for easy visitors navigation and search engine optimization. However, due to many reasons and circumstances, the URL of the website or web page can be attached or appended with suffix which starts with question mark.

For example, forum, CMS (content management system) or web app may add and append session id or referral tracking to the URL, which normally starts with question mark (?) to visitors who are not accepting cookies, and that includes search search engine spiders or crawlers, which potentially causing duplicate content issue. Beside, some web tracking or traffic analytics services such as Google Analytics and FeedBurner may append tracking code to the end of URL, causing redundant URL structures.

Note: The part of URL which starts with ? is declared as query string because according to RFC 2396, in URI (Uniform Resource Identifier), a question mark (?) is used to represent the start of query string. In Apache mod_rewrite, the front part of the URL will return as %{REQUEST_URI} variable, while anything after the question mark will constitute as %{QUERY_STRING}.

mod_rewrite of Apache HTTPD server can be used to remove, strip, clear or truncate the query string from the URL. The rule of the mod_rewrite in order strip and truncate the part of URL after the question mark (together with the ? itself) can take many formats.

Here are a few example rewrite conditions and/or rewrite rules that can be used in .htaccess of the website to instruct mod_rewrite to strip and truncate the query string from URL. Try out to ensure that it works on your website before making the redirect rules live.

RewriteRule ^(.*)$ http://www.domainname.com/$1? [R=301,L]

Replace domain name with the actual domain name of the website. Or,

RewriteCond %{QUERY_STRING} ^session_id
RewriteRule ^(.*)$ $1 [L,R=301]

Replace session_id with the variable name the succeed the question mark in the URL, which is normally consistent to indicate what’s the value is for. Or,

RewriteCond %{THE_REQUEST} ^\?session_id=(.*)$ HTTP [NC] RewriteRule ^$ http://www.domainname.com%{REQUEST_URI} [R=301,L]

Replace the domain and session_id accordingly.

Note that the above .htaccess mod_rewrite trick may not work on WordPress powered blogs which has automatic canonical links redirect enabled (which is default setting), or else it will generate infinite redirect loop.

Related Posts