1

I'm trying to get 2 redirections set on my htaccess file but I can't make it to work.

The desired output is:

  • if the user goes to www.mywebsite.com/page1, it gets redirected to /folder/newPage
  • if the user goes to www.mywebsite.com/page1?a=123, it gets redirected to /folder/anotherPage?a=123

I tried this

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^/page1$ /folder/newPage [R=301,L]

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

I also tried something like this:

RewriteCond %{REQUEST_URI}  ^/page1$
RewriteRule ^(.*)$ /folder/newPage [R=301,L]

RewriteCond %{REQUEST_URI}  ^/page1$
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^(.*)$ /folder/anotherPage%1 [R=301,L]

Note that Rewrite mod is turned on on my apache.

Any idea how to make it work?

1 Answer 1

1

Check through the following:

  1. RewriteEngine On is present before all the rules
  2. AllowOverride directive allows your htaccess files to load
  3. htaccess receives URLs without the leading slashes, unlike server config files, or VHosts file.
  4. .* matches 0 or more characters, thus %{QUERY_STRING} ^(.*)$ also matches empty query strings. Change this to .+.

Final rules should be:

RewriteEngine On

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^page1$ /folder/newPage [R=301,L]

RewriteCond %{QUERY_STRING} ^(.+)$
RewriteRule ^page1$ /folder/anotherPage?%1 [R=301,L]
Sign up to request clarification or add additional context in comments.

6 Comments

RewriteEngine On is set at the beginning of the file. Rewrite mod is ON and working fine. About 3. not sure how to verify this?
@alexmngn Change RewriteRule ^/page1$ to RewriteRule ^page1$
I got the 1st one to work, but not the second one... Seems like the first rule takes over the 2nd rule
@alexmngn I've updated the reply above. You may also try using R=302 instead of 301. Or you might've to clear the browser's cache, to actually see updated rules in effect.
Can't make your rules to work... This one works: RewriteCond %{REQUEST_URI} ^/page1/$ RewriteRule ^(.*)$ /folder/newPage [R=301,L] but also redirects to this page when there is a query param
|

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.