shashwat
shashwat

Reputation: 3

MOD_REWRITE conditional redirection

I've an issue using Apache Mod_Rewrite module,

I'm retrieving three variable from a get request say

$country
$state
$location

I'm successful in rewriting the url locally for example the url

localhost/directory/country/state/location /*is redirected to*/
localhost/directory/result.php?c=country&s=state&l=location

what I want to do is that I want to redirect

localhost/directory/country to localhost/directory/country.php?c=country

and in case of

localhost/directory/country/state to localhost/directory/state.php?c=country&s=state

I'm using following RewriteRule

RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ result.php?s=$1&d=$2&l=$3 [L]

how can I rewrite incase of country and state, and in case if I want to display only country page..

thanks a lot!! please help me out, by giving references to online tutorials and other references..

I would be highly obliged to you to for the same.. :)

Upvotes: 0

Views: 107

Answers (2)

moj
moj

Reputation: 454

I think, you can use two rules:

# localhost/directory/country
RewriteRule ^[^/]+/([^/]+)$  localhost/directory/country.php?c=$1 [L]

# localhost/directory/country/state
RewriteRule ^[^/]+/([^/]+)/([^/]+)$  localhost/directory/state.php?c=$1&s=$2 [L]

Upvotes: 0

Samuel Cook
Samuel Cook

Reputation: 16828

You can use a downward flow in order to recognize if the URL is a country, state, or location with something like:

<IfModule mod_rewrite.c>
    Rewrite Engine On
    RewriteRule ^localhost/directory/([^/\.]+)/([^/\.]+)/([^/\.]+)/ localhost/directory/result.php?c=$1&s=$2&l=$3 [L]
    RewriteRule ^localhost/directory/([^/\.]+)/([^/\.]+)/ localhost/directory/state.php?c=$1&s=$2 [L]
    RewriteRule ^localhost/directory/([^/\.]+)/ localhost/directory/country.php?c=$1 [L]
</IfModule>

Notice how I have started with the longest, the most dynamic URL, first. If you started with the shortest first, in your case country, then the URL_Rewrite would accept that answer first, and you would never hit the other two Rewrites.

Although I find it easier on the PHP parsing side to handle all dynamic URL traffic on one php page, on your case something like result.php that way you can determine the output, and you don't have to worry about jumping around on files.

.htaccess

<IfModule mod_rewrite.c>
    Rewrite Engine On
    RewriteRule ^localhost/directory/([^/\.]+)/([^/\.]+)/([^/\.]+)/ localhost/directory/result.php?c=$1&s=$2&l=$3 [L]
    RewriteRule ^localhost/directory/([^/\.]+)/([^/\.]+)/ localhost/directory/result.php?c=$1&s=$2 [L]
    RewriteRule ^localhost/directory/([^/\.]+)/ localhost/directory/result.php?c=$1 [L]
</IfModule>

result.php

<?php
$location = isset($_GET['l']) ? $_GET['l'] : false;
$state    = isset($_GET['s']) ? $_GET['s'] : false;
$country  = isset($_GET['c']) ? $_GET['c'] : false;

// ...PARSE THE REST OF PHP based off of these variables
?>

Upvotes: 1

Related Questions