Hugo Dias
Hugo Dias

Reputation: 169

Get URL paramters and clean the url using htaccess

Im creating a website that have 2 iframes, the first iframe have a song playing and the second one have the website. Here is my index.php file:

<?php
$base_url = 'http://www.mywebsite.com/site/';
?>
<iframe src="<?php echo $base_url; ?>music.php" frameborder="0" width="960px" height="1px"></iframe>

<?php
$page = $_GET['params'];

switch ($page) {
    case 'home':
        $page = 'home.php';
        break;
    case 'contact':
        $page = 'contact.php';
        break;
}
?>

<iframe src="<?php echo $base_url; ?><?php echo $page ?>" frameborder="0" width="100%" height="100%"></iframe>

And this is my .htaccess

RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ site/index.php?params=$1

It's working fine but what i need is:

When the user try to access http://www.mywebsite.com/contact I need to get this 'contact' for my switch statement and clean the url to http://www.mywebsite.com

Simulation:

  1. Request http://www.mywebsite.com/contact
  2. Get param 'contact'
  3. Load the contact.php file
  4. Clean the url to http://www.mywebsite.com

Thanks in advance!

Upvotes: 1

Views: 184

Answers (3)

Jon Lin
Jon Lin

Reputation: 143906

You can do the first 3 steps with

RewriteRule ^contact$ /contact.php?params=contact [L,QSA]

if you add that before the rules that you already have. But you can't "clean" the URL to http://www.mywebsite.com/, since then it will be indistinguishable from site/index.php?params=home.

For any "contact" page, then:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILEMAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ /$1.php?params=$1 [L,QSA]

You're also going to want to make sure Multiviews is turned off:

Options Multiviews

Upvotes: 2

Unkl Benz
Unkl Benz

Reputation: 33

What do you mean by "clean the URL to http://www.mywebsite.com" ?

Because if you want to transmit the contact parameter you can use the QSA flag which appends query string (Query String Append) but if you just want to clean URL you can do some treatments in your contact.php and then redirect to main page with PHP header function.

He answered while I was typing my answer but I was about to give you Jon Lin's code

Upvotes: 0

anubhava
anubhava

Reputation: 785256

You need just one generic rule like this:

# To internally forward /anything to /anything.php?params=anything
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php?params=$1 [L,QSA]

Upvotes: 1

Related Questions