Search code examples
.htaccesshttp-redirecthttp-status-code-301

htaccess 301 redirect old page to new page dynamicly


i've changed my addresses and made them sef, but some of my links were old and some of them were shared by people, if they would try to enter there, they will see 500 internal server error, as you can imagine, i need to redirect them to new url, i know how to redirect staticly, but don't know how to with dynamicly

for instance, my old link was : mywebsite.com/profile/1, my new link is mywebsite.com/profile/1/johnny-walker

if someone tries to look to my old link, i want them to redirect to my new link

my old rule was:

RewriteRule ^profile/(.*)/?$ profile.php?id=$1 [L] 

my new rule is :

RewriteRule ^profile/([0-9]*)/(.*)/?$  profile.php?id=$1&slug=$2 [QSA,L]

thank you


Solution

  • thats the slug of the guy's name, it comes from database, i call it with get exc., when user registers, its created automaticly, i just wrote it as an example

    What I mean is, before all you had was 1 (the id). From just that id, how do you get the slug? If you can get it from the database, then you need to keep both rules (with some minor changes):

    RewriteRule ^profile/([0-9]+)/([^/]+)/? profile.php?id=$1&slug=$2 [QSA,L]
    RewriteRule ^profile/([0-9]+)/? profile.php?id=$1 [L] 
    

    Then in profile.php you need to do the following:

    1. At the beginning of the file, check if there's a $_GET['slug'] value, if so, server up the page like normal
    2. If there is no slug value, then you need to get the $_GET['id'] (sanitized) value and retrieve the slug out of the database
    3. Using the header() function, create a redirect:

      header('HTTP/1.1 301 Moved Permanently');
      header('Location: /profile/' . $id . '/' . $slug);
      exit();
      

      where the $id is the id and $slug is the slug value from the database.

    That'll make it so when someone requests http://mywebsite.com/profile/1, the rewrite rule will send it to profile.php like it did before where the canonical URL can be crafted and a redirect made.