简体   繁体   English

如何将URL中的数字重写为名称

[英]How to mod_rewrite a number in url to a name

I have a database where I'm picking up information and in this case 我有一个要在其中收集信息的数据库,在这种情况下

user 1023 = madonna

I'm having today an url which is: 我今天有一个网址是:

http://domain.com/welcome.php?p=user&xoxo=1023

and I would like to have the url like this instead 我想改成这样的网址

http://domain.com/user/madonna

Try to use this htaccess 尝试使用此htaccess

Before that you should backup your original htaccess file 在此之前,您应该备份原始的htaccess文件

RewriteEngine On
RewriteBase /

RewriteCond %{QUERY_STRING} ^xoxo=([0-9]*)$
RewriteRule ^(.*)$ http://domain.site/user/madonna [R=301,L]

It cannot be done for a arbitrary number mapping, such as one defined in a database. 对于任意数字映射(例如数据库中定义的数字映射),无法完成此操作。 Instead the application itself should handle the name <-> ID/number processing in this case. 相反,在这种情况下,应用程序本身应处理名称<-> ID /数字处理。

The rewrite (if used) would only be used turn something like /user/madonna into /welcome.php?user=madonna ; 重写(如果使用的话) 只能用于将/user/madonna转换为/welcome.php?user=madonna ; likewise the 'pretty URL' should be generated by the application itself using the already-available username. 同样,“漂亮的URL”应由应用程序本身使用已经可用的用户名生成。

tldr; tldr; The application - not mod_rewrite - is responsible for transformation to/from the username (ie. "madonna") and the corresponding user ID (ie. 1023). 应用程序(不是mod_rewrite)负责与用户名(即“ madonna”)和相应的用户ID(即1023)进行转换。


Anyway, a slightly different approach is to follow what StackOverflow does for URLs; 无论如何,一种稍微不同的方法是遵循StackOverflow对URL所做的操作。 it encodes the ID and a 'friendly' portion. 它编码ID “友好”部分。

For instance a 'friendly question URL' is http//../questions/$id/$title while the only relevant portion of the URL is http://../questions/$id as the title portion is entirely irrelevant to locating the correct question. 例如,“友好问题URL”是http//../questions/$id/$title而URL的唯一相关部分是http://../questions/$id因为标题部分与找到正确的问题。 Similarly, my profile is http://../users/2864740/user2864740 but my username is irrelevant to processing the query and http://../users/2864740 is sufficient to access my profile. 同样,我的个人资料是http://../users/2864740/user2864740但是我的用户名与处理查询无关,并且http://../users/2864740足以访问我的个人资料。

Note: StackOverflow will immediately redirect to the correct-full-friendly-URL if the 'friendly' portion does not match the item referenced by ID; 注意:如果“友好”部分与ID引用的项目不匹配,则StackOverflow将立即重定向到正确的完全友好URL。 this is especially important for something like user accounts to mitigate spoofing. 这对于减轻诸如用户帐户之类的欺骗行为尤其重要。 It also ensures the 'correct' URL is propagated after a title/username change. 它还可以确保在更改标题/用户名后传播“正确的” URL。

In context of the question this would mean the pretty URL is http://domain.com/user/1025/madonna were the ID is already available and easily transformed to a query parameter. 在此问题的上下文中,这意味着该ID已经可用并且可以轻松转换为查询参数的漂亮URL为http://domain.com/user/1025/madonna

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM