douqi1928 2014-02-15 19:57
浏览 33
已采纳

php htaccess的初学者指南

I have just started learning htaccess.

And i want to test one page :

I have one folder called "favs" and inside that i have a php file index and from that i am passing to the page gallery.php with querystring ID

so the url will be :

mainsite.com/favs/gallery.php?id=7

Now i want the url to be like :

mainsite.com/favs/7

and this is the code i write in .htaccess file :

<IfModule mod_rewrite.c>


RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ gallery.php?id=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ gallery.php?id=$1

</IfModule>
  • 写回答

2条回答 默认 最新

  • dongyixiu3110 2014-02-15 20:31
    关注

    Your rules are wrong. You have this:

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^([a-zA-Z0-9_-]+)$ gallery.php?id=$1
    RewriteRule ^([a-zA-Z0-9_-]+)/$ gallery.php?id=$1
    </IfModule>
    

    ^([a-zA-Z0-9_-]+)$ will match everything in the URL after the first slash, as long as there is no slash. There's a slash in mainsite.com/favs/7, so the rule doesn't match, and it looks for an actual directory named /favs/7. What you want is to match only the piece after favs, like this:

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^favs/([0-9]+)/?$ favs/gallery.php?id=$1
    </IfModule>
    

    The code above is what you should put in .htaccess if it is in your root directory. If it is in your /favs directory, then you need to remove the /favs from RewriteRule and add a RewriteBase like this:

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /favs
    RewriteRule ^([0-9]+)/?$ gallery.php?id=$1
    </IfModule>
    

    Note: based on your question, I have eliminated letters, _, and - from the regular expression. If you need to match them, you can tweak the rule above accordingly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?