Search code examples
phpurlurl-routingrouter

Is htaccess file absolutely necessary in router framework?


As I understand it, creating an htaccess file creates a scalability concern since every Apache request requires a lookup of things (as I understand it 4 file accesses).

Since I know exactly when my application needs to look up the "retty urls" - is there a way to just bypass having an .httaccess file and somehow look it up via a file access of my own?

Also, I am able to know before-hand, what the pretty url will look like. How can I do the masking most smoothly?

Here is an example: I made a test page for all trees: http://www.comehike.com/outdoors/trees/trees.php

And my application can know the pretty urls to create.
But I have a single tree.php file here: http://www.comehike.com/outdoors/trees/tree.php?tree_id=24

How can I make it take the tree_id (for db lookup) and also look pretty like this: http://www.comehike.com/outdoors/trees/oak-tree

ps - I am using php


Solution

  • You shouldn't be too concerned with the overhead of using an .htaccess file. It won't have much of an effect on your server load. As for your pretty URL scheme, you can look no further than StackOverflow! Notice the structure of this question's url. It looks like:

    http://stackoverflow.com/questions/[ID]/[QUESTION]
    

    The ID as you probably have guessed, is the unique ID given to every question on SO. The question that follows (your equivalent being the tree name) is simply dummy text. Try changing anything after the /4985258/ and retrying the address. It still sends you to this question. That's because the Mod Rewrite that SO uses ignores everything after the id.

    In your case, I would suggest a URL structure like this:

    http://www.comehike.com/outdoors/trees/24/oak-tree
    

    Using the following htaccess mod_rewrite:

    RewriteEngine On
    RewriteRule ^/outdoors/trees/([0-9]+) /outdoors/trees/tree.php?tree_id=$1
    

    This will match any URL that had an ID in it and send it off to the tree.php script. It's up to you to add the dummy title text to all your links.


    EDIT If you are truly concerned about the minute performance hit you'll take with an htaccess file, you can always move all the code from your htaccess files to your VirtualHost declaration and then declare AllowOverride None to prevent Apache from searching for htaccess files. You can usually find your virtual hosts in /etc/apache2/sites-available/default in Linux or C:\apache\conf\vhosts.conf in Windows.