spiderman February 2016

Clean URL with mod_rewrite including sub directory inside domain

I am trying to use mod-rewrite in .htaccess for implementing clean/pretty URLs.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ details.php?id=$1 [L,QSA]
  • RewriteEngine On turns the engine on.

  • RewriteCond %{REQUEST_FILENAME} !-f does not rewrite anything if the request filename exists, and is a file.

  • RewriteCond %{REQUEST_FILENAME} !-d does not rewrite anything if the request filename exists, and is a directory.

  • RewriteRule ^([^/]+)/?$ details.php?id=$1 [L,QSA] This is the actual rewrite rule. It takes anything after the domain name (anything other than forward slashes), and rewrites it to details.php, passing it as the id parameter.

RewriteRule ^([^/]+)/?$ details.php?id=$1 [L,QSA] is working when request for http://www.domain.com/texas

This is well and good. What I need is that my request URL looks like this: http://www.domain.com/location/texas

and details.php has the below code

<?php
$id = $_GET["id"];
echo "new id is ".$id;
?>

Problem: I couldn't write a valid .htaccess RewriteRule to identify this request http://www.domain.com/location/texas. Please help.

What all I tried?

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^location/?$ details.php?id=$1 [L,QSA] - not working

RewriteRule ^location/[a-z][-a-z0-9]*?$ details.php?id=$1 [L,QSA] - working, but id is displayed blank.

Answers


anubhava February 2016

You can just tweak your existing rule by making starting location/ optional:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:location/)?([^/]+)/?$ details.php?id=$1 [NC,L,QSA]

Post Status

Asked in February 2016
Viewed 3,962 times
Voted 13
Answered 1 times

Search




Leave an answer