Dario Corbelli
Dario Corbelli

Reputation: 33

URL directory as variable with htaccess

my actual .htaccess is

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([_0-9a-zA-Z-]+)? index.php?cl=$1 [L]

and it works good when i type something like sub.domain.com/client1 (then i get the $cl variable in my php code properly). Problem is when i add a final trailing slash like sub.domain.com/client1/ then i get "client1/" in my var!

How can i fix it? I know that the second condition in my htaccess looks for existing directories and skips the rewrite rule but there is no "client1" dir on my server!

Upvotes: 1

Views: 2830

Answers (3)

Frank Yin
Frank Yin

Reputation: 1990

I'm trying to do something very similar, and this works for me:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([^\/]+)$ index.php?arg1=$1&arg2=default [L]
RewriteRule ^([^\/]+)\/$ index.php?arg1=$1&arg2=default [L]
RewriteRule ^([^\/]+)\/([^\/]+)$ index.php?arg1=$1&arg2=$2 [L]
RewriteRule ^([^\/]+)\/([^\/]+)\/$ index.php?arg1=$1&arg2=$2 [L]

The rewrite rules will quit if condition is found so this progressively checks against each longer URL path.

Instead of filtering for only "_0-9a-zA-Z-" characters, this allows all characters not "/" since between each argument I look for the literal "/".

You could extend this for as many arguments as needed. And for URLs that extend beyond the number of arguments this rule accepts, the user should be taken to error 404 page as set by your root .htaccess.

Upvotes: 0

feeela
feeela

Reputation: 29932

" Problem is when i add a final trailing slash like sub.domain.com/client1/ then i get "client1/" in my var!"

That is the expected behavior. You need to strip the slash via PHP afterwards:

$cl = trim( $_REQUEST['cl'], '/' );

or you explode the value to get all folders (if there is another name following after the slash)

$cl = explode( '/', $_REQUEST['cl'] );

Upvotes: 1

Sean Vieira
Sean Vieira

Reputation: 160005

Simply require that the match consume the entire URL path:

# Note the trailing $ on the pattern
RewriteRule ^([_0-9a-zA-Z-]+)?$ index.php?cl=$1 [L]

As it stands currently, your pattern checks to see if the request path starts with (optionally) one or more letters, numbers and / or the underscore and dash characters - but it doesn't otherwise limit itself. So it would match a/b/c/d/e/f/g without complaint. If the variable should never contain anything other than the pattern, adding $ (which means "end of the string" in this case) limits your match.

Upvotes: 0

Related Questions