Search code examples
php.htaccess

php, url hiding with the .htaccess


This is the real url:

http://web/app/index.php?id=1

Here I have used current .htaccess and working fine with me.

Options +FollowSymlinks
RewriteEngine On

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

RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?id=$1

Now the url is : http://web.com/app/index/i and working fine

but here is the problem the real url

http://web.com/app/index.php?id=1&name=abc

How can I set mention url with .htaccess for keep it short or any other good solution for hiding URL-. is it possible to show user only one url like , http://web.com/app but it could go to other pages while the url stay one url static.


Solution

  • If we say, good practice is to rewrite everything to one index page, like this:

    Options +FollowSymLinks
    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
    

    then in your index.php you get uri by $uri = $_SERVER['REQUEST_URI'] :

    http://example.com/app -> $uri = /app
    http://example.com/app/sub-app -> $uri = /app/sub-app
    

    but also query string applies to the $uri variable:

    http://example.com/app/?a=1&b=3 -> $uri = /app/?a=1&b=3
    

    in this case, if you want to examine just uri part before ? question mark:

    $realRri = strtok($uri,'?'); // and you have '/app/' instead of '/app/?a=1&b=3'
    

    next you can examine and manipulate $uri;

    Example:

    $trimmedUri = trim($realRri, '/');
    
    if ($trimmedUri == 'app')
    {
        // you can show app page
    }
    elseif ($trimmedUri == 'contact') 
    {
        // show contact
    }
    else 
    {
        // show 404 page not found
    }
    
    
    // you can have some dynamic also also
    
    if (is_file($filePath = 'custom-page/'.$trimmedUri))
    {
        include $filePath;
    }
    else 
    {
        // 404 page
    }
    

    Final Code (regarding your current script)

    Options +FollowSymlinks
    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.php -f
    
    #rewrite php file
    RewriteRule ^([a-zA-Z]+)$ $1.php 
    #rwwrite with id
    RewriteRule ^([a-zA-Z]+)/([0-9]+)/?$ $1.php?id=$2 
    #rewrite with id and name
    RewriteRule ^([a-zA-Z]+)/([0-9]+)/([0-9a-zA-Z]+)/?$ $1.php?id=$2&name=$3