Without a doubt, SEO (Search Engine Optimization) is one of the main factors studied by Web developers today, as it is directly responsible for how the website will attract new visitors and its positioning in search engines such as Google, Yahoo, Bing and others.
Some time ago, Web developers were not concerned with the semantics of the URL of their pages and it was normal to find something like http://www.site.com.br/noticia.php?id=587. With the advancement of SEO and the improvement of search tools, the concept of friendly url, which consists of URLs in the format http://www.site.com.br/noticia/587/url-semantica-vira-tendendia-no-mercado-web or even http://www.site.com.br/url-semantica-vira-tendendia-no-mercado-web.
In addition to making more sense for the user, who can have an idea of the link's content before even clicking, search engines can use the URL itself to start the process of indexing the content and compare the URL to the page title and H1 tag to check if everyone is talking about the same subject.
In this post I will help you use these resources in your projects.
Preparing the Directing of requests
The first part of implementing a friendly URL is to direct requests to a file in our system to handle these requests, which, in theory, do not exist (there is no file called url-semantica-vira-tendendia-no-mercado-web in your project)
In the code below, I prefixed some extensions to avoid using the url_amigavel.php file, which are file extensions and certainly do not use friendly urls. In this case, if any file in these extensions does not exist, they will be treated using ErrorDocument, which I explained in the post Redirecting HTTP errors using .htaccess
.htaccess
<IfModule mod_rewrite.c>
# Habilita o mod_rewrite
RewriteEngine On
# Caso a URL solicitada não seja um arquivo ou diretório...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# E o arquivo solicitado não seja das extensões abaixo,
# redireciona a requisição para o arquivo "url_amigavel.php" fazer o tratamento
RewriteRule !\.(js|ico|txt|gif|bmp|jpeg|jpg|png|css|log|rss|zip|xml|sql|pdf|doc|docx|xls)$ url_amigavel.php
</IfModule>
Preparing the processing of requests
At this stage, the client will have made the request for our friendly URL, which will have been directed to our PHP file that will handle the URL.
url_amigavel.php
<?php
// Recupera a URL da requisição e seus parâmetros, separando em um vetor dividido pelo caracter "/"
$geturl = explode( "/", str_replace( strrchr( $_SERVER["REQUEST_URI"], "?" ), "", $_SERVER["REQUEST_URI"] ) );
array_shift( $geturl );
// Considera o primeiro parâmetro como o arquivo php
$tipo = $geturl[0];
// Se o arquivo existir, inclui na página. Caso contrário, devemos redirecionar o usuário para uma
// tela amigável de error 404
if ( is_file( "$tipo.php" ) )
{
include "$tipo.php";
}
else
{
echo "
<h1 class='corVermelho'>ERRO: Página não encontrada (Erro 404)</h1>
<p>
<strong>Página Solicitada: <em>{$_SERVER['REQUEST_URI']}</em></strong><br/><br/>
Esta pasta ou página não pôde ser encontrada. Provavelmente ela foi
renomeada, apagada ou simplesmente não existe. Por favor, verifique
se o endereço digitado está correto e tente novamente.
<br/><br/>Caso você necessite realmente de acessar esta pasta ou
arquivo, entre em contato com o <a href='mailto:[email protected]'>Administrador do Sistema.</a>
</p>";
}
?>
Example url: www.seusite.com.br/subcategoria/20/tv-lcd
Return example: Array ( [0] => subcategory [1] => 20 [2] => tv-lcd )
Displaying content in route files
In the case of the example above, the file subcategory.php is my route file that was called through the file url_amigavel.php which will query the database and display the information in the browser to the user. Let's see how our file will identify the parameters entered:
subcategory.php
<?php
// Recupera a URL da requisição e seus parâmetros, separando em um vetor dividido pelo caracter "/"
$geturl = explode( "/", str_replace( strrchr( $_SERVER["REQUEST_URI"], "?" ), "", $_SERVER["REQUEST_URI"] ) );
array_shift( $geturl );
// Recupera o ID da subcategoria, informado na URL (2º parâmetro) e converte para inteiro
$id = intval( $geturl['1'] );
if ( $id == 0 )
{
// Caso o ID seja 0, vou listar as subcategorias para o usuário selecionar qual deseja visualizar
$frmSubcategoria = new frmSubcategoria();
$frmSubcategoria->listar();
}
else
{
// Caso o ID seja > 0, vou consultar os dados dessa subcategoria no banco de dados
$ctrSubcategoria = new ctrSubcategoria();
$subcategoria = $ctrSubcategoria->recuperarObjetoBanco( $id );
// Agora que meu controller criou o objeto, vou exibir os ítens dessa sub-categoria
$frmSubcategoria = new frmSubcategoria();
$frmSubcategoria->visualizar( $subcategoria );
}
?>
Generating the Friendly URL to display on the website
After the structure is ready to work with friendly URLs, comes the main part, which is changing your website's URLs to the friendly URL format.
If you develop using the MVC design pattern, this won't be too much work. Just create a function in each of your models with code similar to this, where the URL is made up of the object ID and the name (which can be title, description, whatever... whatever you use in your project to name the object)
Subcategory.php (Model)
public function retornaUrlAmigavel()
{
$nome_seo = clsUtil::gerarTituloSEO($this->nome);
return "{$_SERVER['HTTP_HOST']}/subcategoria/" . $this->id . "/$nome_seo";
}
If you still develop in a structured way (Study Object Orientation and MVC), you will have to create a function and change your entire website so that whenever you write a URL in your final HTML, it uses this function for that.
Example:
public function retornaUrlAmigavelGenerica($arquivo, $id, $nome)
{
$nome_seo = clsUtil::gerarTituloSEO($nome);
return "{$_SERVER['HTTP_HOST']}/{$arquivo}/{$id}/$nome_seo";
}
Function used to format the name so that it is in the Friendly URL format
public static function gerarTituloSEO( $strTitulo )
{
/* Remove pontos e underlines */
$arrEncontrar = array(".", "_");
$arrSubstituir = null;
$strTitulo = str_replace( $arrEncontrar, $arrSubstituir, $strTitulo );
/* Caracteres minúsculos */
$strTitulo = strtolower( $strTitulo );
/* Remove os acentos */
$acentos = array("á", "Á", "ã", "Ã", "â", "Â", "à", "À", "é", "É", "ê", "Ê", "è", "È", "í", "Í", "ó", "Ó", "õ", "Õ", "ò", "Ò", "ô", "Ô", "ú", "Ú", "ù", "Ù", "û", "Û", "ç", "Ç", "º", "ª");
$letras = array("a", "A", "a", "A", "a", "A", "a", "A", "e", "E", "e", "E", "e", "E", "i", "I", "o", "O", "o", "O", "o", "O", "o", "O", "u", "U", "u", "U", "u", "U", "c", "C", "o", "a");
$strTitulo = str_replace( $acentos, $letras, $strTitulo );
$strTitulo = preg_replace( "/[^a-zA-Z0-9._$, ]/", "", $strTitulo );
$strTitulo = iconv( "UTF-8", "UTF-8//TRANSLIT", $strTitulo );
/* Remove espaços em branco */
$strTitulo = str_replace( " ", "", $strTitulo );
/* Remove preposições */
$strCaracterSeparador = "-";
$arrEncontrar = array("-a-", "-e-", "-i-", "-o-", "-u-", "-p-", "-em-", "-de-", "-do-", "-da-", "-dos-", "-das-", "-com-", "-um-", "-uma-", "-para-");
$arrSubstituir = $strCaracterSeparador;
$strTitulo = str_ireplace( $arrEncontrar, $arrSubstituir, $strTitulo );
return $strTitulo;
}
And the URL www.seusite.com.br/tv-lcd?
In this post, I mentioned a very common type of friendly URL too, which is the format www.seusite.com.br/tv-lcd for example. This type of friendly URL is a little more complicated to implement, since an ID was not provided in the URL for you to consult directly in the database, only the text.
For this implementation, we will need to create a field in the database to store the friendly URL generated, allowing us to query our database using the title (tv-lcd) and thus identifying which URL this title is associated with.
Normally, a table is created for this, containing the friendly URLs and the respective pages that will be displayed (using include or require in PHP), as there are several different types of content (subcategories, products, categories, news, etc.) and this approach would not be restricted to just one type of content.
Another (easier) approach would be to include the ID and content type at the end of the URL, in the format www.seusite.com.br/tv-lcd-subcategoria-20 and when handling the request for your subcategoria.php file you would make this change:
// Recupera a URL da requisição e seus parâmetros, separando em um vetor dividido pelo caracter "-"
$geturl = str_replace("/", "", explode( "-", str_replace( strrchr( $_SERVER["REQUEST_URI"], "?" ), "", $_SERVER["REQUEST_URI"] ) ) );
$numParametros = count($geturl);
$id = $geturl[$numParametros - 1];
$arquivo = $geturl[$numParametros - 2];
Using what you learned in this post, you can implement this smoothly. If you have any questions, leave your comment and I will answer it.
Final considerations
Implementing a friendly URL in your project will not be simple and quick, as some SEO changes usually are. It's really a bit of work and expensive, especially if you're not used to the object-oriented paradigm and the MVC design pattern.
The concept of a friendly URL is extremely important for SEO, and it is increasingly common to find websites that use this concept. Those who haven't joined this yet (friendly URLs have been a reality for a few years) are already well behind their competitors, so don't waste time.
Comentários (0)
Carregando comentários…