且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

htaccess的URL重写/重定向 - 像Facebook并

更新时间:2023-09-12 08:41:46

一步URL重写一步...

URL rewriting step by step...

您已经做了这部分 - 你想要 example.com/peter 来是你的用户所看到的

You've done this part - you want example.com/peter to be what your user sees

从技术上讲,可以产生巨大的硬codeD重写规则列表,如:

Technically, you could produce a huge list of hard coded rewrite rules, e.g.

RewriteRule ^peter$ mypage.php?id=324
RewriteRule ^alice$ mypage.php?id=325
RewriteRule ^bob$ mypage.php?id=326

但是,当你有很多用户,这不是特别有效的。

But that's not particularly efficient when you have a lot of users.

您mypage.php会接受一个I​​D,但你真的需要修改它,以便它可以接受一个可能的用户名(但假定它包含各种垃圾)。比方说,你决定允许其采取另一个查询字符串参数提示。所以,现在你必须得到这样的工作的URL: example.com/mypage.php?hint=peter

Your mypage.php will accept an id, but you'll really need to modify it so that it can accept a possible username (but assume it will contain all sorts of garbage). Let's say you decide to allow it to take another query string argument 'hint'. So now you have to get a URL like this working: example.com/mypage.php?hint=peter

确保您的脚本会产生一个404响应任何的用户名是不理解。

Ensure your script produces a 404 response for any username it doesn't understand.

要做到这一点会是这样的一种方式 - 先的RewriteCond 线确保规则只触发如果请求不符合实际的文件。该重写规则会导致请求被mypage.php处理,但传入其余的URL为提示参数中。该'QSA'的部分是短关于'查询字符串追加',这意味着任何查询字符串present在原始URL被添加到写规则。在'L'的意思是'最后',所以没有更多的规则进行调用来处理这个请求。

One way to do this would be something like this - the first RewriteCond line ensures the rule only fires if the request doesn't match an actual file. The RewriteRule will cause the request to be handled by mypage.php, but passing in the rest of the URL as the 'hint' paramter. The 'qsa' part is short for 'query string append', which means any query string present in the original URL is added to the written rule. The 'l' means 'last', so that no further rules are invoked to handle this request.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-z]+)$ mypage.php?hint=$1 [qsa, l]

在mypage.php你再看看用户使用的提示。

In mypage.php you'd then look up the user using the hint.

请注意我已经pretty的限制性格局,小写字母只允许序列。这将有助于确保您的脚本不为每个404你的网站可能会产生调用。

Note I've been pretty restrictive in the pattern, only sequences of lower case letters allowed. This will help ensure your script isn't invoked for every 404 your site might produce .