我已经构建了我的网站的URL,如Stack Overflow URL.我的网址如下.
http://www.example.com/1255544/this-is-the-url-text
Run Code Online (Sandbox Code Playgroud)
在此URL中,1255544是id并且this-is-the-url-text是URL标题文本,两者都存储在数据库中.我注意到Stack Overflow URL在id的基础上工作.假设这是一个Stack Overflow URL
http://stackoverflow.com/questions/15679171/new-way-to-prevent-xss-attacks
Run Code Online (Sandbox Code Playgroud)
在此URL中,15679171是帖子的ID.当我将此ID更改为15706581未触及new-way-to-prevent-xss-attacks并按Enter键时,URL自动更改为以下URL:
http://stackoverflow.com/questions/15706581/simplecursoradapter-does-not-load-
external-sqlite-database-id-error
Run Code Online (Sandbox Code Playgroud)
当我试图删除URL标题文本的一些部分,如下所示
http://stackoverflow.com/questions/15679171/new-way-to-preve
Run Code Online (Sandbox Code Playgroud)
它会自动更正URL,如下所示:
http://stackoverflow.com/questions/15679171/new-way-to-prevent-xss-attacks
Run Code Online (Sandbox Code Playgroud)
这意味着基于id 15679171和相关的URL标题文本从数据库中检索数据,根据id new-way-to-prevent-xss-attacks附加.
我也想这样做.但问题是,我不明白,如果有人更改URL的ID,标题文本应该自动更改.我该怎么做呢?
我想到了以下几点:
$url_id = $_GET["id"];
$url_txt = $_GET["url_txt"];
$qry = "SELECT * FROM mytable WHERE url_id = '{$url_id}' LIMIT 1";
$data = mysql_query($qry);
$data_set = mysql_fetch_array($data);
if($url_txt== $data_set["url_txt"]) {
// proceed further
} else {
$rebuilt_url = "http://www.example.com/" . $url_id . "/" . $data_set["url_txt"];
header("Location: {$rebuilt_url}") // Redirect to this URL
}
Run Code Online (Sandbox Code Playgroud)
这是否是执行此操作的正确有效方法?有解决方案吗?
你的代码看起来很不错,在我的Stack Overflow的一个答案中,我也提出了类似的方法.但是,我建议只做一个小改进.代替:
header("Location: {$rebuilt_url}");
Run Code Online (Sandbox Code Playgroud)
你应该做:
header ('HTTP/1.1 301 Moved Permanently');
header("Location: {$rebuilt_url}");
Run Code Online (Sandbox Code Playgroud)
这将使浏览器积极地缓存这些URL,并且每次都不会执行代码和SQL查询.
还检查:
在 URL 重写中,您可以将 URL 重写为更友好的外观。看看下面的网址
当你对其进行 URL 重写时,它就变成了这样
http://www.downloadsite.com/Nettools/Messengers
Run Code Online (Sandbox Code Playgroud)
URL重写需要在Apache配置上设置(重写规则),这样它会在PHP解释请求之前重写你的URL,这样你就可以获得你想要获取的确切资源
RewriteRule ^/category$ /content.php
RewriteRule ^/category/([0-9]+)$ /.php?id=$1
RewriteRule
^/category/([0-9]+),([ad]*),([0-9]{0,3}),([0-9]*),([0-9]*$)
cat.php?id=$1&sort=$2&order=$3&start=$4
Run Code Online (Sandbox Code Playgroud)
好吧,我无法在这里向您解释所有内容,但下面我为您提供了一些链接,您可以在其中了解 URL 重写。
这是创建友好 URL 的最佳技巧!
资源:
http://www.cyberdesignz.com/blog/website-design/url-rewriting-top-5-ways-of-php-url-rewriting/
http://www.fliquidstudios.com/2009/01/06/url-rewriting-with-apache-and-php-a-simple-example/