Url rewriting mod_rewrite

2019-08-03 06:11发布

问题:

I am working with mod_rewrite for the first time. I am going to present a scenario. Just let me know whether it's possible or not.

suppose I have a database table with three attributes table(id,title,parentid).

and my url to access the particular content looks like this:

example.com/content.php?id=some_value

Now, for some_value id , title is some_title. Is it possible that such that

example.com/some_title/

can be renamed to above url.OR

example.com/content.php?id=some_value&title=some_title

I may also have url such as :

example.com/content.php?id=some_value&title=some_title&parenttitle=parent_title

In which case entered url should be something like this:

example.com/parent_title/some_title/

If I haven't made myself clear do let me know. Again this is my first attempt at mod_rewrite. So even a small information will be very helpful.

回答1:

Here's what you can put in your .htaccess file

  # /id - search an ID
  RewriteRule ^([0-9]+)(/?)$ /content.php?id=$1 [QSA,L]                                                                   

  # /title - search a title
  RewriteRule ^([a-z0-9\-\ ]+)$ /content.php?title=$1 [NC,QSA,L]                                                          

  # /parent/child - search parent and child
  RewriteRule ^([a-z\-\ ]+)/([a-z0-9\-\ ]+)$ /content.php?parent=$1&child=$2 [NC,QSA,L]                                   

  # /id/name - search id and title
  RewriteRule ^([0-9]+)/([a-z0-9\-\ ]+)$ /content.php?id=$1&child=$2 [NC,QSA,L]                                           

  # /search/some_title - search for a title
  RewriteRule ^search/([a-z0-9\-\ ]+)(/?)$ /search.php?q=$1 [NC,QSA,L]    

etc...



回答2:

NO! URL rewriting DO NOT generate anything JUST change things you have to something else! you should put id,title or parentid in URL if you're going to use them!