Undoubtedly, SEO (Search Engine Optimization) is one of the main study factors for web developers today as it is directly responsible for how the website will attract new visitors and for positioning it on search engines like Google, Yahoo, Bing and others.
Some time ago, web developers had no concern about the semantics of their page URLs and it was normal to find something like http://www.site.com/noticia.php?id=587. With the advancement of SEO and the improvement of search engines, the concept of friendly url, which consists of URL's in the format http://www.site.com.br/noticia/587/url-semantica-vira-tendendia-no-mercado-web or same http://www.site.com.br/url-semantica-vira-tendendia-no-mercado-web.
In addition to making more sense for the user himself, who can get an idea of the content of the link even before clicking, search engines can use the URL itself to begin indexing the content and compare the URL to the page title. and the H1 tag to make sure everyone is talking about the same subject.
In this post I will help you use this feature in your projects.
Preparing Requirements Steering
The first part of the friendly URL implementation is to direct requests to a file in our system to handle those requests, which in theory do not exist (there is no file called url-semantic-turn-on-web-market in your project). )
In the code below, I prefixed some extensions not to handle using the url_amigavel.php file, which are file extensions and certainly do not use friendly url. In this case, if any files in these extensions do not exist, they will be treated using the ErrorDocument, which I explained in the post. HTTP error redirection using .htaccess
.htaccess
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<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 Request Handling
At this stage, the client will have requested our friendly URL, which will be directed to our PHP file which will handle the URL.
url_amigavel.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?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.yoursite.com/subcategory/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 informed parameters:
subcategory.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?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 site
After the structure is already ready to work with a friendly URL, the main part comes, which is to change the URLs of your website by the friendly URL format.
If you develop using the MVC design pattern, this will not be too much work. Just create a function in each of your models with code similar to this one, where the URL is composed of the object ID and the name (which can be a title, description, in short… what do you use in your project to name the object)
Subcategory.php (Model)
1 2 3 4 5 |
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 site so that whenever you type a URL in your final HTML, it will use this function for that.
Example:
1 2 3 4 5 |
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 to be Friendly URL format
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
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; } |
What about the URL www.yoursite.com/tv-lcd?
In this post, I mentioned a very common friendly URL type too, which is the format www.yoursite.com/tv-lcd for example. This kind of user-friendly URL is a bit trickier to implement since no URL ID was provided for you to query straight into the database, just text.
For this implementation, we will need to create a field in the database to store the generated friendly URL, allowing us to query our database by title (tv-lcd) and thus identifying which URL this title is associated with.
Usually a table is created for this, containing the friendly URLs and their pages that will be displayed (using include or require in PHP), as there are many different types of content (subcategories, products, categories, news, etc.) and this approach would not be restricted to just one content type.
Another (easier) approach would be to include the content ID and type at the end of the URL in the format www.yoursite.com/tv-lcd-subcategory-20 and when dealing with the request of your subcategory.php file you would make this change:
1 2 3 4 5 6 |
// 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 questions, leave your comment and I will answer it.
Final considerations
Implementing friendly URLs in your project will not be as simple and fast as some SEO changes usually are. It's really a little work and costly, especially if you're not used to the object-oriented paradigm and MVC design pattern.
The concept of friendly URL is extremely important for SEO, and it is increasingly common to find websites that use this concept. Anyone who hasn't joined this yet (friendly URL has been a reality for a few years now) is already well behind the competition, so don't waste time.