堆栈溢出url是如何工作的


How do Stack Overflow URLs work?

我已经建立了我的网站的url,如Stack Overflow url。我的网址如下:

http://www.example.com/1255544/this-is-the-url-text

在这个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

其中15679171为文章的id。当我在不触及new-way-to-prevent-xss-attacks的情况下将此id更改为15706581并按Enter键时,URL自动更改为以下URL:

http://stackoverflow.com/questions/15706581/simplecursoradapter-does-not-load-
external-sqlite-database-id-error

当我试图删除URL标题文本的某些部分时,比如下面的

http://stackoverflow.com/questions/15679171/new-way-to-preve

它会自动更正URL如下:

http://stackoverflow.com/questions/15679171/new-way-to-prevent-xss-attacks

表示根据id 15679171从数据库中检索数据,并根据id附加相关的URL标题文本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
}

执行此操作是否正确且有效?有解决办法吗?

你的代码看起来很不错,在我的Stack Overflow回答中,我也建议过类似的方法。然而,我只建议一个小小的改进。而不是:

header("Location: {$rebuilt_url}");

你应该这样做:

header ('HTTP/1.1 301 Moved Permanently');
header("Location: {$rebuilt_url}");

这会让浏览器积极缓存这些url,你的代码和SQL查询不会每次都执行。

也检查:

  1. 。如果URL是坏的,做点什么
  2. 。htaccess重写友好url

如果您使用Apache,我认为您必须了解URL重写

在URL重写中,您将URL重写为更友好的外观。看看下面的URL

http://www.downloadsite.com?category=34769845698752354

当你对它进行URL重写时,它变成了这样的

http://www.downloadsite.com/Nettools/Messengers

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

好吧,我不能在这里解释所有的事情,但是下面我提供了一些链接,你可以在那里学习URL重写。

这是你可以做的最好的hack来创建友好的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/
  • http://www.sitepoint.com/guide-url-rewriting/
  • 。htaccess重写友好url