How do I rewrite a name to an id?

2020-05-02 15:29发布

I'm trying to rewrite the following URL

www.domain.com/category.php?id=13

to:

www.domain.com/category/cat-name

I've followed some .htaccess tutorials but I couldn't. How can I make it work?

标签: .htaccess url
1条回答
等我变得足够好
2楼-- · 2020-05-02 15:59

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.

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.

First make a .htaccess in your www-root:

RewriteEngine on
RewriteRule ^category/[^/]+$ /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" );
}

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

查看更多
登录 后发表回答