As far as I can tell I’m doing what needs to be done based on mod_rewrite examples I’ve found but there’s an obvious problem that I can’t seem to solve.
I’m calling up city pages like this:
<a href=“cities/Adrian”>Adrian</a>
In my .htaccess file I have this:
RewriteEngine On
RewriteRule ^cities/([a-zA-Z\.\ ]+)/?$ cities.php?city=$1 [NC,L]
When I click one of the city links in a page, the rewrite works fine. It changes this:
and the page is called up as expected. But the city links are in the footer of every page so the visitor can click a 2nd city link from a city page if desired. The problem is that then the friendly URL ends up looking like this:
First, you should NOT escape the dot character in the range definition - the space is properly escaped.
The problem you’re having is what I’ve labeled the “missing support files” problem, i.e., because the request was made of the cities directory, the browser thinks it’s in that directory when served cities.php from the DocumentRoot of the website. The relative links in your script all point to cities/{city} which, relative to cities, is cities/cities/{city}.
There are two ways to get around this: Use absolute links or use the <base> tag in your script (so the browser will know where it is in your directory structure). There is also a third way: Use R=301 in your redirection but that will show the true location to the visitor, too, as a webmaster normally wants that hidden.
Thanks DK. I tried out your base tag suggestion and that worked. Much appreciated. But I have a follow up question. For my development machine, where everything is local (http://mysite.local/public_html) I use this:
What’s the best way to set it up so as not to have to change back and forth between the testing environment and the live location? Is there a good way to do this?
If you only have one “handler script,” hardcode the location there. Aw, if you’re going to add a boatload of PHP code (yours or ScallioXTX’s), it’s still easier to add the <base> tag which SHOULD be the script’s path/filename, not just the path.
I’d heard of problems with PHP correctly identifying it’s location (confusion over directory level) but never bothered (color me lazy) to verify that as the “hardcode the handler script” seems to be easier - UNLESS you use a header script across many pages which cross directory levels (ANY file within the <base> tag is fine).