FoxyFish
FoxyFish

Reputation: 892

htaccess redirect query string to a path

So i have a htaccess rewrite that makes a query string to a path like so..

RewriteRule ^page/(.*)$ page.php?query=$1

This works fine and using the above i can access the page via both page.php?query= and /page/query/ but how can i make it so that if the page is accessed by the page.php?query= method, it automatically redirects to the path version?

I've tried the following but i don't think i wrote it correctly...

RewriteCond %{HTTP_HOST} ^www\.webaddress\.com\/page\.php\?query\=$
RewriteRule ^(.*)$ http://www.webaddress.com/page/$1 [R=301,L] 

Any help to fix this would be appreciated. Thanks.

Upvotes: 1

Views: 1920

Answers (2)

Amit Verma
Amit Verma

Reputation: 41219

You can use the following

RewriteEngine On
#url redirection from old url to the new one
#redirect /page.php?query=foo to /page/foo
RewriteCond %{THE_REQUEST} /page.php\?query=([^\s]+) [NC]
RewriteRule ^.+$ /page/%1? [L,R]
#url rewiring from new url to the old one
# rewrite /page/foo to /page.php?query=foo
RewriteRule ^page/(.*)$ page.php?query=$1 [L]

Upvotes: 3

Abhishek Gurjar
Abhishek Gurjar

Reputation: 7476

Try it before your internal rewrite rule.

RewriteEngine On
RewriteCond %{REQUEST_URI} ^(.+)\.php
RewriteCond %{QUERY_STRING} ^(.+)\=(.+)
RewriteRule ^ http://%{HTTP_HOST}/%1/%2/%3? [R=301]

Upvotes: 0

Related Questions