URL Rewriting including title

后端 未结 2 981
忘了有多久
忘了有多久 2021-01-07 01:41

Initially i succeed to rewrite the url using id

with the htaccess code:

RewriteRule ^link/([0-9]+)\\.html$ sub_index.php?link_id=$1          


        
2条回答
  •  借酒劲吻你
    2021-01-07 02:26

    First, your rewrite code is not correct:

    RewriteRule ^link/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ sub_index.php?link_id=$1
    

    Your link_id is $2, your title is $1. So you should use:

    RewriteRule ^link/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ sub_index.php?link_id=$2
    

    Then you should use a slug function for your title, so it's more url friendly. I use something like this:

    function slug($string, $spaceRepl = "-") {
      // Replace "&" char with "and"
      $string = str_replace("&", "and", $string);
    
      // Delete any chars but letters, numbers, spaces and _, -
      $string = preg_replace("/[^a-zA-Z0-9 _-]/", "", $string);
    
      // Optional: Make the string lowercase
      $string = strtolower($string);
    
      // Optional: Delete double spaces
      $string = preg_replace("/[ ]+/", " ", $string);
    
      // Replace spaces with replacement
      $string = str_replace(" ", $spaceRepl, $string);
    
      return $string;
    }
    

    slug("Trekking in Nepal") will be trekking-in-nepal, so your link will be:

    /link/trekking-in-nepal/6.html
    

    It should work then with your rewrite code.

    Also, I like to rewrite my links like this:

    /link/trekking-in-nepal-6.html
    

    For this I use the following:

    RewriteRule ^link/([a-zA-Z0-9_-]+)-([0-9]+)\.html$ sub_index.php?link_id=$2
    

    Good luck!

提交回复
热议问题