简体   繁体   中英

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

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

在此输入图像描述


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:

在此输入图像描述


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

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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM