3

I am trying to perform a 301 redirect in .htaccess and I need to remove the query string ?view=full. Here is what I have that is not working:

RewriteRule ^/contact/?view=full$ /contact/ [R=301,L]

I have tried a variety of different solutions with no luck.

1
RewriteRule ^/contact/?view=full$ /contact/ [R=301,L]

The RewriteRule pattern matches against the URL-path only, which notably excludes the query string. So, the above directive won't match the required URL. To match the query string you need to use an additional condition and check against the QUERY_STRING server variable.

Also, in .htaccess (directory context) the URL-path matched by the RewriteRule pattern does not start with a slash, because the directory-prefix that is first removed from the URL that is matched by the pattern ends with a slash. So, again, the directive will not match the requested URL because of the slash prefix.

Also, the query string from the request is copied through to the substitution string by default - unless you explicitly discard or create a new query string. So, the above directive won't remove the query string either.

Try the following instead, near the top of your .htaccess file:

RewriteCond %{QUERY_STRING} ^view=full$
RewriteRule ^(contact/)$ /$1 [QSD,R=302,L]

This matches the URL /contact/?view=full exactly. And redirects to /contact/. The QSD (Query String Discard) flag (Apache 2.4) on the RewriteRule directive discards the query string from the substitution string.

The $1 is a backreference to the captured group in the RewriteRule pattern, ie. the value contact/. This simply saves typing/repetition.

Note that this is currently a 302 (temporary) redirect. If this is intended to be permanent then only change it to a 301 once you have tested that it works OK. 301s are cached persistently by the browser, so can make testing problematic.

You should clear your browser cache before testing.

Reference:

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.