How to rewrite these urls for country, state, city?

↘锁芯ラ 提交于 2019-12-12 04:35:23

问题


I have a site where articles being submitted from worldwide and I record the location of them as Country -> State -> City, for that I am generating URLs like:

site/location/countryname/statename/cityname

I have a single php file which can take care of coming request and gets values in query string, now the problem is how to write mod_rewrite so it can have URL like above?

PS: It should not pass empty values if someone deletes the statename or countryname, means URL can be:

site/location/countryname
site/location/countryname/statename
site/location/countryname/statename/cityname

But can not be:

site/location//statename/cityname
site/location/countryname//cityname

In above urls if countryname is deleted then statename shouldnt be treated as countryname. Reading file name is location.php

Thanks,


回答1:


Try to write the rules where longer condition comes first -

RewriteRule ^page/(.*)/(.*)/(.*)/(.*)/(.*)$ page.php?site=$1&location=$2&countryname=$3&statename=$4&cityname=$5 [QSA]
RewriteRule ^page/(.*)/(.*)/(.*)/(.*)$ page.php?site=$1&location=$2&countryname=$3&statename=$4 [QSA]
RewriteRule ^page/(.*)/(.*)/(.*)$ page.php?site=$1&location=$2&countryname=$3 [QSA]



回答2:


  • First of all make sure there's no slash (/) between each slash. It's the ([^/]*).
  • Then make sure it's never empty. It's the + instead of the *. So, now, it's the ([^/]+).
  • Then stop immediately the rule once it has been validated: use the L directive.
  • Don't forget to make the query string follow via the QSA directive.

Here's what your final rules should be:

RewriteRule ^page/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)$ page.php?site=$1&location=$2&countryname=$3&statename=$4&cityname=$5 [QSA,L]
RewriteRule ^page/([^/]+)/([^/]+)/([^/]+)/([^/]+)$ page.php?site=$1&location=$2&countryname=$3&statename=$4 [QSA,L]
RewriteRule ^page/([^/]+)/([^/]+)/([^/]+)$ page.php?site=$1&location=$2&countryname=$3 [QSA,L]

And if that's not enough:

Two hints:

If you're not in a hosted environment (= if it's your own server and you can modify the virtual hosts, not only the .htaccess files), try to use the RewriteLog directive: it helps you to track down such problems:

# Trace:
# (!) file gets big quickly, remove in prod environments:
RewriteLog "/web/logs/mywebsite.rewrite.log"
RewriteLogLevel 9
RewriteEngine On

My favorite tool to check for regexp:

http://www.quanetic.com/Regex (don't forget to choose ereg(POSIX) instead of preg(PCRE)!)




回答3:


Ok I have got a way to do that:

RewriteRule ^bylocation/([-a-z_]+)(?:/([-a-z_]+)(?:/([-a-z_]+))?)?/?$ location.php?country=$1&state=$2&city=$3 [NC,L,QSA]

This single rule can take care, instead of three rules.



来源:https://stackoverflow.com/questions/9052830/how-to-rewrite-these-urls-for-country-state-city

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!