robert sinior robert sinior - 3 months ago 16
PHP Question

htaccess redirection just if url has parameter

I searched for it. But I couldn't find what I need.

I have a url like


mydomain.com/1hr6rry5


Currently when a user clicks on this link he will go actually to


mydomain.com/profile.php?id=1hr6rry5


And if the url be like mydomain.com/ he will go to


mydomain.com/home.php


I mean when url has a parameter he goes to profile.php and when there is not a parameter he goes to home.php .

By now I'm doing redirection with php, which looks so slow. I want to make it faster by doing it with htaccess.

How can I do it?

my htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/\.]+)/?$ profile.php?id=$1 [L]


my index.php for redirection

<?php

if(empty($_GET['act_id']))
{
header('Location: home.php');
exit();
}

header('Location: profile.php?id='.$_GET['act_id']);

?>

Answer

Using only Apache configurations (and then, .htaccess), you can try this:

  1. Url rewrite:

    <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^(.*)$ profile.php?id=$1 [L,QSA]
    </IfModule>
    
  2. To define "home.php" as a landing page (or an index) of your website, open your Apache configuration file for your website (for example, default.conf or apache2.conf or httpd.conf):

    <Directory /path/to/your/webproject>
        DirectoryIndex home.php index.php index.html
    </Directory>
    
Comments