8

I would like to rewrite URL's with htaccess to better readable URL's and use the $_GET variable in PHP
I sometimes make use of a subdomain so it has to work with and without. Also are the variables not necessary in the url. I take a maximum of 3 variables in the URL

the URL sub.mydomain.com/page/a/1/b/2/c/3 should lead to sub.mydomain.com/page.php?a=1&b=2&c=3 and the url sub.mydomain.com/a/1/b/2/c/3 should lead to sub.mydomain.com/index.php?a=1&b=2&c=3 where $_GET['a'] = 1

I came up with this after searching and trying a lot

RewriteEngine on
RewriteRule ([^/]+)\.domain.com/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)$ $1.domain.com/$2.php?$3=$4&$5=$6&$7=$8 [QSA,NC]  
RewriteRule ([^/]+)\.domain.com/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)$ $1.domain.com/index.php?$2=$3&$4=$5&$6=$7 [QSA,NC]  
RewriteRule ([^/]+)\.domain.com/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)$ $1.domain.com/$2.php?$3=$4&$5=$6 [QSA,NC]  
RewriteRule ([^/]+)\.domain.com/([^/]+)/([^/]+)/([^/]+)/([^/]+)$ $1.domain.com/index.php?$2=$3&$4=$5 [QSA,NC]  
RewriteRule ([^/]+)\.domain.com/([^/]+)/([^/]+)/([^/]+)$ $1.domain.com/$2.php?$3=$4 [QSA,NC]  
RewriteRule ([^/]+)\.domain.com/([^/]+)/([^/]+)$ $1.domain.com/index.php?$2=$3 [QSA,NC]  
RewriteRule ([^/]+)\.domain.com/([^/]+)$ $1.domain.com/$2.php [L,QSA,NC]  

but what I get is an not found server error

I'm not that good at this so maybe I oversee something.
Also I would like it to work with and without a slash at the end

Should I make use of RewriteCond and/or set some options?

Thanks in advance.

MeSo2
  • 450
  • 1
  • 7
  • 18
Dediqated
  • 901
  • 15
  • 35
  • 3
    Rather than doing this splitting in mod_rewrite, why not just have a simple catchall rule (`RewriteRule ^(.*)$ index.php?p=$1`) and then parse the url however you'd like to in php. Most CMSes and web frameworks do it this way, since it's more flexible, easier to maintain, and didn't depend on Apache. – Lie Ryan Nov 23 '12 at 09:06
  • @LieRyan and then to a max of 9 variables, good idea I'll try the next time I got the same problem. – Dediqated Nov 23 '12 at 10:11
  • 1
    I cant help but say... Q-Dance FTW! – Alexander Johansen Nov 04 '14 at 12:38

1 Answers1

8

When using RewriteRule, you don't include the domain name in the line. Also, make sure you turn on the RewriteEngine first. Like this:

RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)$  index.php?$1=$2
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)$  index.php?$1=$2&$3=$4
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)$  index.php?$1=$2&$3=$4&$5=$6

The first line will rewrite sub.mydomain.com/a/1 to sub.mydomain.com/page.php?a=1, the second rewrites sub.mydomain.com/a/1/b/2 to sub.mydomain.com/page.php?a=1&b=2, and so on.

ONOZ
  • 1,390
  • 2
  • 11
  • 19
  • Yeah thanks that works great! My bad, RewriteEngine was turned on. I'll edit the question and put it in the code block. – Dediqated Nov 23 '12 at 08:53