Configuration of . htaccess to access several PHP files within the same folder

Asked

Viewed 3,361 times

2

I’ve been beating myself since yesterday with my configuration .htaccess, my original URL is like this (2 is the page number):

www.example.com/categoria/produtos/2 

Categoria is a briefcase inside of mine public_html and produtos stays within it.

So far so good, only inside categoria, I have several other files .php.

Currently my .htaccess this way:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l 
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
RewriteRule ^(.*)$ produto.php?page=$1

In short, for all the pages inside my categoria, are being redirected to produto.php and the pages do not pass, always the result is in the same!

The structure of the code is like this:

  $url = $_GET['page']; //Pegando página selecionada na URL
  $dados = explode('/', $url);
  $dir = $dados[0]; 
  $page = $dados[1]; 

  if(empty($_GET['page'])){
    $page=1;
  }
  if($page >= '1'){
    $page = $page;
  }
  else{
    $page= '1';
  }

And in the pagination this so:

echo "<li><a href='/categoria/produto.php/".($page+1)."'>NEXT</a></li>";
  • Add another condition, for the categories.

  • I recommend an htaccess with RewriteRule (.*) index.php [QSA,L] and let the system route the URL. This makes it easier for you to manage routes.

3 answers

1

.HTACCESS

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} \.php$
RewriteRule (.*) index.php [QSA,L]


ROUTE

// www.meusite.com/categoria/produtos/2 -> carros/novos
$url = ltrim( parse_url( $_SERVER['REQUEST_URI'] , PHP_URL_PATH ) , '/' );

$router= explode( '/' , $url );
$router[0] // categoria
$router[1] // produtos
$router[2] // 2

All information from your URL will be in the array router.
You decide how to check the indices of $router[X].

There are several ways to route the URL, this is the simplest, however, keeps logic in PHP, easier to include, change or remove any category.

Your HTACCESS will accept any URL, but it’s up to PHP to validate and decide controller responsible for each route street segment...

www.domain.com/contact
www.domain.com/category
www.domain.com/category/search
www.domain.com/category/products
www.domain.com/category/products/2
... N combinations

0

to url

http://www.meusite.com/categoria/produtos/556

try this

RewriteEngine On
RewriteRule ^(categoria/produtos/[0-9]+)$ produto.php?page=$1

or

RewriteEngine On
RewriteRule ^([a-z]+/[a-z]+/[0-9]+)$ produto.php?page=$1

dai in php product.php

<?php  
$url = $_GET['page']; //Pegando página selecionada na URL  
$dados = explode('/', $url);  
$dir = $dados[0];  
$subdir = $dados[1];  
$page = $dados[2];  

if(empty($_GET['page'])) {  
$page = 1;

} else if ($page >= '1') {  
$page = $page;  

} else {  
$page= '1';  

}

this site is good to simulate rewrite . htaccess http://htaccess.madewithlove.be/

  • Nothing, Returns Internal Server Error ... Just to reinforce, man. htaccess placed within the category, to apply the config to pages within this folder, correct? ... About Nginx, I use a hosting site, ai complica rsrs ..

  • William, it wasn’t .. what happens, all the pages in the category then listing the content of my index.php that is inside public_html ...

  • Some guy tries this one more, puts this . htaccess inside the category folder RewriteRule ^(produtos/[0-9]+)$ produto.php?page=$1 this only takes the URL typed with "products/[0-9]+" after category.

  • Not yet William, now it shows only the products.php, but does not pass the page. rsrs

  • edited my answer, tested here and it worked, . htaccess is fucking even kkk

0

Before answering the question itself, an important detail that can cause a lot of confusion in your tests: do not forget to set the base path!

This can be done in . htaccess, but the simplest way is to do it by html:

<!-- inclua isso no "head" do html -->
<base href="http://a_url_do_seu_site.com/" />

So, especially when working with many folders and subfolders, files with sections and subsections, one does not miss the absolute beginning of the navigation for reference of all links.

In your case, if "categories" is always the basis, you could do it:

<!-- inclua isso no "head" do html -->
<base href="http://www.meusite.com/categoria/" />

And any return of friendly urls would start with "product/page", ignoring the categories, which would be your "home", so to speak.

Getting back to your problem, this type of situation is what we call "multiple entries" when there is more than one file. php to call, instead of just an index.php. In this case . htaccess can be configured in two ways.

First Option

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?p=$1

Here nothing changes regarding the single input case, but the existing files are also called by the "user friendly" query string. To do this, just agree that the first parameter (in your case) is a folder, and the second is the file name. For example:

www.meusite.com/categoria/produtos/2 

extracting the query srtring:

$qs = explode("/", ltrim($_GET['p'], "/"));

$caminho = $qs[0];
$arquivo = $qs[1].".php";
$parametro = $qs[2];
// e assim sucessivamente...

The most important thing in this method is that you understand that you need to work out a way to standardize the addresses and folder and file structure of your project. It is easier (and beneficial in many ways) to plan the project well, than to burn phosphorus with . htaccess.

Second Option (not recommend, but there is)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1\.php

What changes is that you can now pass complete paths, and the last parameter (no bar) will be the name of the php file. I think it goes without saying that there are no advantages to this approach in your case, mainly because it hinders the passage of query strings.

Finally, I see something that could be changed in your pagination code, which is like this:

if(empty($_GET['page'])){ 
    $page=1;              
}                         
if($page >= '1'){
    $page = $page;
} else {
    $page= '1';
}

When would it be more interesting to do this:

$page = 1;                   // por padrão, page é sempre 1
$dir  = "produtos";          // outro padrão, por exemplo
if (!empty($_GET['page'])) { // todo o resto só faz sentido se houver dados
    $dados = explode("/", ltrim($_GET['pages'], "/"));   
    $dir  = $dados[0];
    $page = empty($dados[1]) ? 1 : $dados[1]; // só por garantia...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.