I would like to get this final url:
'ideal url'
domain/services/city/name/
from this url:
'real url'
domain/page.php?s=services&c=city&a=name
This should work both when user type the 'ideal' url and when 'real' url is clicked from a button.
I would like this works also with domain/services/
as domain/page.php?s=services
or domain/services/city/
as domain/page.php?s=services&c=city
.
I'm not asking the code but what is the best practice to achieve this result.
Should I use only htaccess and write commands for every case, or do I have to do something else?
The best practice will be to write a query parser. See examples in for example TinyMVC framework, or serach google for router, front controller, dispatcher etc.
It can be hard to achieve because you have custom parameter names, like 'c' and 'a'. So you have to write some map that will assign human readable parameter names to variable names like:
'city' => 'c'
'name' => 'a'
Your query parser can also auto-assign variables in some way like:
/domain/services/c=london/n=peter/
This kind of dispacher can run with all your links if you remap all requests to one php file in .htaccess (typically index.php), excluding images, swf, css, js etc.
It's your decision how you will plan your url routing logic. Remember about special characters ane url encoding.
Consider getting parameter values in numerical order like "first parameter", "second parameter" to create a universal url pattern like /module/action/param1/param2/ etc. So you can always get a parameter by number, independly from its name.
You can of course write commands in htaccess, but it would be problematic when adding new actions.
If you want to heave those "ideal" urls even if user clicks a link, submit form etc. you cannot only change .htaccess or write router. You also have to change links/actions in code or write URL builder like
<a href="<?php buildUrl( 'modulke' , 'action' , 'param1' , 'param2' ); ?>">aaaa</a>
Enable mod_rewrite and .htaccess through httpd.conf
and then put this code in your .htaccess
under DOCUMENT_ROOT
directory:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
# redirects /page.php?s=services&c=city&a=name to /services/city/name/
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+page\.php\?s=([^&]+)&c=([^&]+)&a=([^&]+) [NC]
RewriteRule ^ /%1/%2/%3? [R=301,L]
# forwards /services/city/name/to /page.php?s=services&c=city&a=name
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ /page.php?s=$1&c=$2&a=$3 [L,QSA]
PS: Note that above rules only take care of /services/city/name/
URI. To handle /services/city/
and /services/
you will need to add similar set of rules (1 redirect and 1 forward for each URI; go from most specific towards most generic)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With