How to Dynamically Rewrite a URL like Facebook

前端 未结 4 365
滥情空心
滥情空心 2021-01-17 03:49

I\'ve written my site using PHP and unfortunately the Artist profiles are currently like this:

website.com/profiles.php?id=xxx

That way I can GET the id and

相关标签:
4条回答
  • 2021-01-17 03:50

    You can use Gumbo's answer, but you also have one possible shortcut:

    You can also redirect the /artistname url to /profiles.php?id=xxx by using a 404 handler

    Here's how you would do it:

    1. create a file called /router.php
    2. Edit your .htaccess file and add this line into it: ErrorDocument 404 /router.php
    3. Make router.php lookup the artist ID and redirect to /profiles.php?id=xxx - if nothing is found, router.php can redirect to another 404 page or do a 404 header + message

    The good thing about this method, is that you don't have to have mod_rewrite enabled. (if that's a problem)

    0 讨论(0)
  • 2021-01-17 04:00

    You can use a URL "slug", whereby a record has a unique name, ie:

    id     name             slug
    001    Stack Overflow   stack-overflow
    

    then you could perform a query such as:

    SELECT `fields` FROM `table` WHERE `slug`='$slug'
    

    where slug is the value from the URL.

    There are alternatives as I'm sure will be provided.

    0 讨论(0)
  • 2021-01-17 04:12

    If you do not want the ID in the URL, the artist names need to be the new ID and thus unique.

    In that case you can do the following in the .htaccess file in your document root directory to rewrite /<artistname> internally to /profiles.php?name=<artistname>:

    RewriteEngine on
    RewriteRule ^([a-z]+)$ profiles.php?name=$1
    

    Here the artist name is also restricted to only consist of alphabetic letters. For other characters (especially . and /) you should take into account not to allow values that conflict with existing files (e.g. profiles.php). And if you derive the URL artist names from their real names, make sure not to allow conflicts either. In that case you will still need the artificial ID to make the URL path unique.

    0 讨论(0)
  • 2021-01-17 04:12

    Firstly, you need alter your artists table, adding a new column for define an alias for artists, like 'david-matthews-band', create an index unique to prevent confusions with homonym artists.

    You need edit your profile.php to find artists by alias, like website.com/profile.php?q=david-matthews-band

    Create a rewrite rule to transform website.com/profile/david-mattews-band to website.com/profile.php?q=david-matthews-band:

    RewriteEngine On
    RewriteRule ^profile/*  profile.php?q=$1
    
    0 讨论(0)
提交回复
热议问题