Andrew Andrew - 2 years ago 139
PHP Question

HTACCESS: Dynamic rewrite url with multiple variables

I've been working on this for a couple of days now and I'm wondering if anyone could point me in the right direction please... I'm trying to pass two variables in my rewrite.

Unless the given url is a file or directory, I'd like all urls to be dynamically rewritten as follows:


example.com/category -> example.com/index.php?p=category

example.com/category/page ->
example.com/index.php?p=category&article=page

example.com/category2/page ->
example.com/index.php?p=category2&article=page


I'm having a hard time trying to turn the following in something dynamic:

RewriteRule ^category/(.+?)$ ?p=category&article=$1 [L]


I'm trying this but it doesnt work:

RewriteRule ^(.+?)/(.+?)$ ?p=$1&article=$2 [L]


...also trying this but it doesnt work either:

RewriteRule ^(.*)/(.+?)$ ?p=$1&article=$2 [L]


I'm trying to avoid putting in the following to make it work:

RewriteRule ^category2/(.+?)$ ?p=category2&article=$1 [L]


Here is the full code:

Options +FollowSymLinks
RewriteEngine On

RewriteRule ^category/(.+?)$ ?p=category&article=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ?p=$1 [L]





UPDATE:

This actually did it for me:

RewriteRule ^([^/]+)(/([^/]+))? ?p=$1&article=$2 [L]


Thank you!!
Andrew

Answer Source

I'm not an expert but I think this will do it for you:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([^/]+)/([^/]+) index.php?p=$1&article=$2         [L]

Where [^/]+ matches everything except /, result when tested on htaccess.madewithlove.be

enter image description here


EDIT:

as I totally forgot that the second parameter is optional, the great update in the OP almost did it except the fact that it adds a / at the start of parameter2 value, because $2 is capturing the outer group, while we need the inner one, as shown in this image:

enter image description here


Instead replace $2 with $3 and this should fix it:

RewriteRule ^([^/]+)(/([^/]+))? ?p=$1&article=$3   [L]

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download