url rewriting with htaccess? [duplicate]

2019-07-12 08:55发布

问题:

This question already has an answer here:

  • rewrite url with htaccess [closed] 1 answer

My problem: I want to write a .htaccess rule for. www.asdf.com/city.php?city=New-York to www.asdf.com/New-York but also with that I have other pages such as www.asdf.com/country.php?country=USA which I would like to appear as www.asdf.com/USA and www.asdf.com/state.php?country=LA which I would like to appear as www.asdf.com/LA

Pretty confused how to do that.

回答1:

If you wish to have identical url's for 3 completely different things, you are forced to use a php page to 'detect' what kind of 'thing' it is and 'route' your request to a specific page.

The following (untested) two rules will redirect all listed 'ugly' url's above to a fancy url and the fancy url to a php page that determines what page it should use for the request. %2 is a back reference to the second capturing group in a RewriteCondition. The trailing ? clears the query string.

RewriteCond %{QUERY_STRING} (city|country)=([^&]*)
RewriteRule (country\.php|city\.php|state\.php) %2? [R=301,L]

RewriteRule ^([^/]*)$ myRouter.php?url=$1 [END]

With a file myRouter.php with something like:

<?php
  $url = $_GET['url'];

  if( isCity( $url ) ) {
    $city = $url;
    include( 'city.php' );
    exit();
  } elseif( isCountry( $url ) ) {
    $country = $url;
    include( 'country.php' );
    exit();
  }
  #etc....
?>

More logical would it be to use different fancy url's for different things, e.g. /country/USA for country.php?country=USA, /state/LA for state.php?country=LA and /city/New-York for city.php?city=New-York.

This can easily be done with the following (untested) htaccess and produces more logical url's:

RewriteCond %{QUERY_STRING} (city|state|country)=([^&]*)
RewriteRule ^(country|city|state)\.php$ $1/%2? [R=301,L]

RewriteRule ^(country|city|state)/(.*)$ $1.php?$1=$2 [END]