Mod rewrite using .htaccess

前端 未结 2 832
一个人的身影
一个人的身影 2020-12-19 14:01

I am trying to Rewrite my mode using this info[copy from a website], but it\'s not working .. what\'s wrong with it and plz give a correct answer..

The Apache rewrit

相关标签:
2条回答
  • 2020-12-19 14:45

    Try

    RewriteRule ^product/([a-zA-Z0-9_]+)/?$ product.php?id=$1 [L]
    
    0 讨论(0)
  • 2020-12-19 15:01

    You seem to have misunderstood what the rewrite module (and your rules specifically) actually does.

    Quite simply when you browse to:

     localhost/abc/product.php?id=23
    

    The RewriteRule isn't invoked and shouldn't be doing anything. There's nothing wrong here, you're just browsing to the wrong URL

    URL Transformation

    http://www.yoursite.com/product/123         <- URL that user goes to
    http://www.yoursite.com/product.php?id=123  <- Rewritten URL that the server sees
    

    RewriteRule(s) explanined

    A rewrite rule is broken down into three parts (not including the RewriteRule part...)

    1. The regex that it matches against the url
    2. The url that it transforms into
    3. Additional options

    Given your rule:

    RewriteRule ^product/([^/.]+)/?$ product.php?id=$1 [L]
    

    The regex is: ^product/([^/.]+)/?$
    The new url : product.php?id=$1
    The options : [L]

    This means that the user browses to the nice url http://www.yoursite.com/product/123 (and all of your links point to the nice URLs) and then the server matches against the regex and transforms it to the new URL that only the server sees.

    Effectively, this means that you have two URLs pointing to the same page... The nice URL and the not-nice URL both of which will take you to the same place. The difference is that the not-nice / standard URL is hidden from the general public and others pursuing your site.


    Regex

    The reason why http://mysite.com/product/image.jpg is not being redirected is because of the regex that you use in your RewriteRule.

    Explanation

    ^product/([^/.]+)/?$
    
    • ^ => Start of string
    • product/ => Matches the literal string product/
    • ([^/.]+) => A capture group matching one or more characters up until the next / or .
    • /?$ => Matches an optional / followed by the end of the string

    Given the URL:

    http://mysite.com/product/image.jpg
    

    Your regex matches product/image but then it encounters . which stops the matching... As that isn't the end of string $ the rule is invalidated and thus the transform never happens.

    You can fix this by changing your character class [^/.] to just [^/] or - my preferred method - to remove the character class and simply use .+ (seeing as your capturing everything to the end of the string anyway

    RewriteRule ^product/([^/]+)/?$ product.php?id=$1 [L]
    RewriteRule ^product/(.+)/?$ product.php?id=$1 [L]
    
    0 讨论(0)
提交回复
热议问题