Remove variable from base URL with htaccess

2019-02-15 12:40发布

问题:

I've been trying to rewrite a URL such as

www.somesite.com/?x=372

into a url

www.somesite.com/

My current code does not seem to work

RewriteEngine On

RewriteCond %{QUERY_STRING} x=(.*)

RewriteRule http://www.somesite.com/ [R=301,L]

I've looked up countless ways of trying to do it with htaccess and still no success.

回答1:

If you simply want to redirect a client to remove the query string (everything after the ? in the URL), then you can try this:

RewriteEngine On
RewriteCond %{QUERY_STRING} x=(.*)
RewriteRule ^ http://www.somesite.com/? [R=301,L]

You've got most of it right, it seems, but your rule needs to have a match, and your target (the http://www.somesite.com/) needs a ? at the end so that any query string before the rewrite won't get appended.

In Apache 2.4 or newer you can use the QSD query string discard flag:

RewriteEngine On
RewriteCond %{QUERY_STRING} x=(.*)
RewriteRule .* http://www.somesite.com/ [R=301,L,QSD]