我如何重写一个名称,一个id? [英] How do I rewrite a name to an id?
问题描述
我试图重写以下网址
www.domain.com/category.php?id=13
到
www.domain.com/category/cat-name
我跟着一些的.htaccess教程,但我不能。我怎样才能使它工作?
I've followed some .htaccess tutorials but I couldn't. How can I make it work?
推荐答案
您不能改写一个号码的名称,除非你有把这一数字为名称的一些方法。这意味着,在HTTP守护进程级别(阿帕奇/ htaccess的),你没有足够的信息来重定向。在PHP中的重定向,请参阅这个。
You cannot rewrite a number to a name, unless you have some way of translating that number to a name. This means that on the http deamon level (Apache/.htaccess) you don't have enough information to redirect it. For redirects in php, see this.
既然你问在PHP重写,我来回答这个问题了。有没有这样的事情在一个PHP文件重写。内部重写映射一个网址(例如: www.domain.com/category/cat-name
),并让服务器执行不同的URL(例如: WWW .domain.com / category.php?ID = 13
)。这发生在HTTP守护程序级别,你的情况阿帕奇。
Since you ask about rewrites in php, I'll answer that too. There is no such thing as rewriting in a php file. An internal rewrite maps one url (e.g. www.domain.com/category/cat-name
) and lets the server execute a different url (e.g. www.domain.com/category.php?id=13
). This happens on the http deamon level, in your case Apache.
首先做出的.htaccess在您的www根:
First make a .htaccess in your www-root:
RewriteEngine on
RewriteRule ^category/[^/]+$ /category.php
在category.php:
In category.php:
if( strpos( $_SERVER['REQUEST_URI'], 'category.php' ) != FALSE ) {
//Non-seo url, let's redirect them
$name = getSeoNameForId( $_GET['id'] );
if( $name ) {
header( "Location: http://www.domain.com/category/$name" );
exit();
} else {
//Invalid or non-existing id?
die( "Bad request" );
}
}
$uri = explode( '/', $_SERVER['REQUEST_URI'] );
if( count( $uri ) > 1 ) {
$name = $uri[1];
} else {
//Requested as http://www.domain.com/category ?
die( "Bad request" );
}
这将请求重定向到的类别/名称,如果你要求category.php?ID =数字和网址,如果你要求的类别/名称获取名称
This will redirect requests to category/name if you request category.php?id=number and get the name from the url if you request category/name
这篇关于我如何重写一个名称,一个id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!