Home > Blockchain >  rewrite urls with optional parameters and avoid confusion
rewrite urls with optional parameters and avoid confusion

Time:12-06

assuming I have these 5 urls (with parameters) and want to create url rewrite for each of them. these URLs are possible results of a search form. (the search by form is done with 3 filters which are optional : speciality, region, city)

search.php?speciality=cardiologist&region=my_region&city=my_city
doctor/cardiologist/my_region/my_city

search.php?speciality=cardiologist&region=my_region
doctor/cardiologist/my_region

search.php?speciality=cardiologist
doctor/cardiologist

search.php?region=my_region&city=my_city
doctor/my_region/my_city

search.php?region=my_region
doctor/my_region

how would I be able to use htaccess/regex rewrite rules to manage these urls and avoid confusion

I tried this but I think that it creates confusion so it doesn't work well (I'm begginer in regex)

RewriteRule ^doctor/([a-zA-Z\-] ) search.php?speciality=$1 [L]
RewriteRule ^doctor/([a-zA-Z\-] ) search.php?region=$1 [L]
RewriteRule ^doctor/([a-zA-Z\-] )/([a-zA-Z\-] ) search.php?speciality=$1&region=$2 [L] 
RewriteRule ^doctor/([a-zA-Z\-] )/([a-zA-Z\-] ) search.php?region=$1&city=$2 [L] 
RewriteRule ^doctor/([a-zA-Z\-] )/([a-zA-Z\-] )/([a-zA-Z\-] ) search.php?speciality=$1&region=$2&city=$3 [L] 

what solutions do you recommend?

CodePudding user response:

search.php?speciality=cardiologist&region=my_region&city=my_city
doctor/cardiologist/my_region/my_city

You can't resolve this ambiguity in .htaccess/mod_rewrite if speciality, region and city are all independently optional and entirely variable.

The query string resolves this ambiguity by including a parameter name. If you remove the identifying "name" (as you are doing in the URL-path) it's entirely ambiguous.

Just from a human-readable stand point, how would you know what the following URLs represent?

  • doctor/foo/bar
  • doctor/baz/qux

If all values of speciality, region and city are unique in your application then you can potentially resolve this ambiguity in your PHP script by looking up the values in your DB to determine which value is the speciality, region or city. But this puts a significant overhead on your application as you are having to perform several additional DB lookups. And if they are not unique (now or in the future) then this problem is impossible to resolve.

You need something in the URL-path that identifies each value: speciality, region or city. For example:

  • doctor/s-cardiologist/r-my_region/c-my_city
  • doctor/r-my_region/c-my_city
  • doctor/s/my_speciality/r/my_region/c/my_city
  • doctor/r/my_region/c/my_city

Or use a placeholder when a value is not available:

  • doctor/my-speciality/my-region/my-city
  • doctor/none/my-region/my-city
  • doctor/none/none/my-city

Although are these solutions any better than the original query string?

  • Related