1

I've no experience with regex, and the redirect rule I'm trying to put in my .htaccess file for a WordPress site is having no effect.

I want to redirect:

https://example.com/example/?person=name

to

https://example.com/example/people/name

From reading, I figure my rule ought to be:

RewriteRule  \?person=(.*) https://example.com/example/people/$1 [R=301,L]

What am I missing/doing wrong?

1 Answer 1

1

From reading, I figure my rule ought to be:

RewriteRule  \?person=(.*) https://example.com/example/people/$1 [R=301,L]

You can't match the query string part of the URL using the RewriteRule pattern. The RewriteRule pattern matches against the requested URL-path only. To match the query string you need to use a condition and check the QUERY_STRING server variable.

For example:

RewriteCond %{QUERY_STRING} ^person=([^&]*)
RewriteRule ^example/$ /example/people/%1 [QSD,R=302,L]

This needs to go before the existing WordPress directives.

This matches the URL-path exactly as stated in your question, ie. /example/.

%1 (as opposed to $1) is a backreference to the last matched condition, ie. the value of the person URL parameter, that occurs as the first URL parameter.

The QSD (Query String Discard) flag (Apache 2.4+) is required to remove the query string from the target URL. If you are still on Apache 2.2 then append an empty query string (ie. append a ?) to the end of the subsitution string instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Found I needed to add ? after %1 in order to remove the query string, but works perfectly.
@JohnG Yes, sorry I forgot that! If you are on Apache 2.4+ then you can use the QSD flag instead. I've updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.