如何生成URL重定向类似使用的.htaccess和PHP来计算器? [英] How to generate url redirects similar to stackoverflow using .htaccess and php?

查看:131
本文介绍了如何生成URL重定向类似使用的.htaccess和PHP来计算器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

正如人们在计算器的URL结构注意到,每一个问题都有一个ID后面的问题标题。例如:

As one would notice in stackoverflow's url structure, every question has an id followed by the question title. For example:

http://stackoverflow.com/questions/1039725/how-to-do-url-re-writing-in-php

以上网址有问题ID: 1039725 现在的问题标题是:如何到DO-的URL重写功能于PHP

The url above has the question id: 1039725 The question title is: how-to-do-url-re-writing-in-php

只是为了玩弄这个网址,即使一个人进入一些垃圾的东西为标题的一部分,同样的问题内容,​​只要这个问题id是有显示的。例如下面的网址也将给予相同的内容。

Just to play around with this url, even if one were to enter some junk stuff for the title part, the same question content will be displayed as long as the question id is there. For example the following url will also give the same content.

http://stackoverflow.com/questions/1039725/some-junk-stuff-title

更多IMORTANTLY 地址栏会自动更改为:

and MORE IMORTANTLY the url bar automatically changes to:

http://stackoverflow.com/questions/1039725/how-to-do-url-re-writing-in-php

我的提问

据我所知,计算器也许使用的.htaccess重定向的问题ID一些后端所有的URL(比方说PHP页面)来处理它。但是如何在地址栏更改为实际的问题标题自动?

I understand that stackoverflow perhaps uses .htaccess to redirect all urls with the question id to some backend (let's say php page) to process it. But how does the address bar change to the actual question title automatically?

最重要的是:如何实现没有重定向到任何真正的文件夹显示完整的URL?即我不想用头()重定向在PHP中的一些文件夹。

Most important thing is: how to achieve displaying the complete url without redirecting to any real folder? i.e. I don't want to use header() redirection in php to some folder.

这样做是为了避免贪图重定向造成不必要的网络文件夹中的每个问题。

The idea is to avoid creating unnecessary web folders for each question just for the sake of redirection.

推荐答案

这比你想象的少神奇。每一个岗位都有数据库中的一个相关联的蛞蝓,其中它的存储(或者说是塞在飞行中产生的,这并不重要)。只有从数据库中检索,虽然在数字ID是非​​常重要的。之后,这是一个简单的检查(伪code):

It's less magical than you might imagine. Every post has an associated slug in the database where it's stored (or that slug is generated on the fly, it doesn't matter). Only the numeric id is really important when retrieving from the database though. After that it's a simple check (in pseudocode):

$question = getFromDatabase($_GET['id']);
if ($question['slug'] != $_GET['slug']) {
    header("Location: /questions/$question[id]/$question[slug]", true, 301);
}

仅此而已,无所不及。

Nothing more, nothing less.

这是只针对搜索引擎优化的目的而进行的,所以URL始终包含问题的标题以目前的形式,并保持该URL规范。

This is only done for SEO purposes, so the URL always contains the title of the question in its current form and to keep that URL canonical.

这篇关于如何生成URL重定向类似使用的.htaccess和PHP来计算器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆