URL Rewrite query database?

隐身守侯 提交于 2019-12-02 14:38:18

问题


I'm trying to understand how URL rewriting works. I have the following link.

mysite.com/profile.php?id=23

I want to rewrite the above url with the users first and last name.

mysite.com/directory/liam-gallagher

From what I've read however you specify the rule for what the url should be output as, but how do I query my table to get each user name?

Sorry if this is hard to understand, I've confused myself!


回答1:


You are looking at this from the wrong direction. You can't do that kind of automatic url rewrite. The best is to create an all over url rewrite:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

and create a specific name for a user in the db that will be used as an url.

+---------+----------+------+-----------+----------------+
| user_id | username | name | surname   | url            |
+---------+----------+------+-----------+----------------+
|      23 | liam     | Liam | Gallagher | liam-gallagher |
+---------+----------+------+-----------+----------------+

Now when someone accesses your http://mysite.com/directory/liam-gallagher, you can read the last entry and find the user_id in you database and make your script do the rest.

The other way is as Pekka suggested. Create an url like http://mysite.com/directory/23/liam-gallagher and read the id from the link. But I personally don't like that kind of urls. They are just fast/lazy workarounds in my opinion.




回答2:


Something like (just a draft, adapt to your own needs...):

RewriteEngine On
RewriteRule ^([a-zA-Z]+)/([a-zA-Z]+)/([0-9]+)/([-0-9a-zA-Z]+)/?$ /$1/$2.php?id=$3 [L]



回答3:


One approach I've used works as follows.

Make a rewrite rule, e.g.

mysite.com/directory/(.*)

That redirects to:

mysite.com/profile.php?user=%1

Having %1 as the parameter captured from the rule.

Then grab the user from the query parameter on the profile page and fetch the ID for that user from the db.

http://httpd.apache.org/docs/current/mod/mod_rewrite.html



来源:https://stackoverflow.com/questions/12972608/url-rewrite-query-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!