utlamn
utlamn

Reputation: 135

Redirection is not working with mod_rewrite in htaccess

I need to redirect few URIs having query string like:

/pages/foo.bar?pageId=123456 to http://some.site/spam/egg/

/pages/foo.bar?pageId=45678 to http://another.site/spaming/egging/

I have this in my htaccess:

RewriteEngine On

RewriteCond %{REQUEST_URI} ^/pages/foo.bar$
RewriteCond %{QUERY_STRING} ^pageId=123456$
RewriteRule ^.*$ http://some.site/spam/egg/ [R=301,L]

RewriteCond %{REQUEST_URI} ^/pages/foo.bar$
RewriteCond %{QUERY_STRING} ^pageId=45678$
RewriteRule ^.*$ http://another.site/spaming/egging/ [R=301,L]

But its not working, showing 404. What am i doing wrong?

Upvotes: 2

Views: 90

Answers (2)

anubhava
anubhava

Reputation: 785256

You need to move these 2 rules i.e. before all other rules just below RewriteEngine On line as other rules might be overriding this.

(Based on your comments) Your culprit rule is this rule:

RewriteRule . index.php [L]

Which is actually rewriting every request to index.php and changing value of REQUEST_URI variable to /index.php thus causing this condition to fail:

RewriteCond %{REQUEST_URI} ^/pages/foo.bar$

Upvotes: 1

Patrick Fournier
Patrick Fournier

Reputation: 688

From your example, you get redirected to

http://some.site/spam/egg/?pageId=123456
http://another.site/spaming/egging/?pageId=45678

You can use your browser developer tools to see the redirection (in the Network tab).

Maybe the query strings in the redirected URL lead to a 404? You can add a ? at the end of your redirection to clear the query string:

RewriteCond %{REQUEST_URI} ^/pages/foo.bar$
RewriteCond %{QUERY_STRING} ^pageId=45678$
RewriteRule ^.*$ http://another.site/spaming/egging/? [R=301,L]

Upvotes: 1

Related Questions