Reputation: 63
I try to convert a url parameter in folders using RewriteRule. Anyone can help me?.
Origin: search.php?term=red&cat=colors Destination: /search/red/colors
Upvotes: 2
Views: 3990
Reputation: 143906
The top part of this answer clarifies how URLs get rewritten and redirected. Using "convert" is not really clear, as there's 2 completely different things that can happen.
To change a URL like /search.php?term=red&cat=colors
to the nicer looking variation, you need to match against the actual request and redirect the browser:
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD)\ /search\.php\?term=([^&]+)&cat=([^&\ ]+)
RewriteRule ^ /search/%2/%3/? [L,R=301]
This makes it so when someone types in their browser the URL: http://mysite.com/search.php?term=red&cat=colors
, they get externally redirected to http://mysite.com/search/red/colors
, changing the URL in the address bar.
Then in order to internally rewrite the nicer looking URL and route it back to the php script:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?search/([^/]+)/([^/]+)/?$ /search.php?term=$1&cat=$2 [L]
This does the reverse, but only internally so that the URL in the browser's address bar remains unchanged while the content is served from search.php
. You can do one or the other depending on what your need is, or you can do both if you need this to happen in both directions.
Upvotes: 3