url rewriting with htaccess? [duplicate]

落爺英雄遲暮 提交于 2020-01-04 11:05:06

问题


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]


来源:https://stackoverflow.com/questions/17158767/url-rewriting-with-htaccess

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