Search code examples
phpajaxwebserver-sideweb-hosting

How to load a specific page for any given pathname URL


Let's say I have a web-page called www.mysite.com


How can I make it so whenever a page is loaded like www.mysite.com/58640 (or any random number) it redirects to www.mysite.com/myPHPpage.php?id=58640.


I'm very new to website development so I don't even really know if I asked this question right or what languages to tag in it...



If it helps I use a UNIX server for my web hosting with NetWorkSolutions


Solution

  • Add this to your .htaccess file in the main directory of your website.

    RewriteEngine on
    RewriteBase /
    RewriteRule ^([0-9]+)$ myPHPpage.php?id=$1 [L]
    

    Brief explanation: it says to match:

    • ^ from start of query/page
    • [0-9] match numbers
    • + any matches of 1 or more
    • $ end of page requested

    The parentheses part say to look for that bit and store it. I can then refer to these replacement variables in the new url. If I had more than one parentheses group then I would use $2, $3 and so on.

    If you experience issues with the .htaccess file please refer to this as permissions can cause problems.

    If you needed to capture something else such as alphanumeric characters you'd probably want to explore regex a bit. You can do things such as:

    RewriteRule ^(.+)$ myPHPpage.php?id=$1 [NC, L]
    

    which match anything or get more specific with things like [a-zA-Z0-9], etc..

    Edit: and @Jonathon has a point. In your php file wherever you handle the $_GET['id'] be sure to sanitize it if used in anything resembling an sql query or mail. Since you are using only numbers that makes it easy:

    $id = (int)$_GET['id']; // cast as integer - any weird strings will give 0
    

    Keep in mind that if you are not going to just use numbers then you will have to look for some sanitizing function (which abound on google - search for 'php sanitize') to ensure you don't fall to an sql injection attack.