Home > Enterprise >  htaccess RewriteRule for URL shortener
htaccess RewriteRule for URL shortener

Time:01-09

I have a working RewriteRule that for example http://mydomain/stack rewrites to decoder.php?decode=stack and then redirects it to the correct website because decoder.php looks up in its database what the redirect should be.

Options  FollowSymLinks -Indexes -MultiViews  
RewriteEngine on
RewriteRule ^phpmyadmin$ phpmyadmin [L]
RewriteRule ^([\w\d-]{1,})$ decoder.php?decode=$1 [L]

But now I need "more levels". First I tried with a dot. Eg. http://mydomain/l1.stack, but I couldn't get my RewriteRule to work. Anyway: the better approach would be http://mydomain/l1/stack to rewrite to decoder.php?level=l1&decode=stack or http://mydomain/a1/wH4tever. to decoder.php?level=a1&decode=wH4tever.. The "levels" that I want should be fixed in the .htaccess, but the "decode" could be any string.

One problem: I don't get any RewriteRule to work with what I want :-(.

CodePudding user response:

Here a simple rule for a single, fixed and literal "level" string "l1":

RewriteEngine on
RewriteRule ^l1/([\w\d-]{1,})$ decoder.php?level=$1&decode=$2 [L]
RewriteRule ^([\w\d-]{1,})$ decoder.php?decode=$1 [L]

This should do if there are multiple fixed literal "level" strings (here "l1" or "a1")

RewriteEngine on
RewriteRule ^(l1|a1)/([\w\d-]{1,})$ decoder.php?level=$1&decode=$2 [L]
RewriteRule ^([\w\d-]{1,})$ decoder.php?decode=$1 [L]

That would be the generic variant:

RewriteEngine on
RewriteRule ^([\w\d-]{1,})/([\w\d-]{1,})$ decoder.php?level=$1&decode=$2 [L]
RewriteRule ^([\w\d-]{1,})$ decoder.php?decode=$1 [L]

Test yourself: htaccess.madewithlove.com

  • Related