Apache 301 redirect with get parameters

2.5k Views Asked by At

I am trying to do a 301 redirect with lightspeed webserver htaccess with no luck.

I need to do a url to url redirect without any related parameters.

for example:

from: http://www.example.com/?cat=123

to: http://www.example.com/some_url

I have tried:

RewriteRule http://www.example.com/?cat=123 http://www.example.com/some_url/ [R=301,L,NC]

Any help will be appreciated.

1

There are 1 best solutions below

2
On

Thanks for adding your code to your question. Once more we see how important that is:

your issue is that a RewriteRule does not operate on URLs, but on paths. So you need something like that instead:

RewriteEngine on
RewriteRule ^/?$ /some_url/ [R=301,L,NC,QSD]

From your question it is not clear if you want to ignore any GET parameters or if you only want to redirect if certain parameters are set. So here is a variant that will only get applied if some parameter is actually set in the request:

RewriteEngine on
RewriteCond %{QUERY_STRING} (?:^|&)cat=123(?:&|$)
RewriteRule ^/?$ /some_url/ [R=301,L,NC,QSD]

Another thing that does not really get clear is if you want all URLs below http://www.example.com/ (so below the path /) to be rewritten, or only that exact URL. If you want to keep any potential further path component of a request and still rewrite (for example http://www.example.com/foo => http://www.example.com/some_url/foo), then you need to add a capture in your regular expression and reuse the captured path components:

RewriteEngine on
RewriteRule ^/?(.*)$ /some_url/$1 [R=301,L,NC,QSD]

For either of this to work you need to have the interpretation of .htaccess style files enabled by means of the AllowOverride command. See the official documentation of the rewriting module for details. And you have to take care that that -htaccess style file is actually readable by the http server process and that it is located right inside the http hosts DOCUMENT_ROOT folder in the local file system.


And a general hint: you should always prefer to place such rules inside the http servers host configuration instead of using .htaccess style files. Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).