Barakna Obama
Barakna Obama

Reputation: 25

HTACCESS Rewrite with 2 and 3 variables

I have 3 variables in my URL I need on my website: page, category, and subcategory.

index.php?page=orders&cat=meat&sub=beef

Like so

My RewriteRules look like this:

EDIT:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#Rewrite Page
RewriteRule ^([A-Za-z0-9-]+)/?$  index.php?page=$1 [NC,L]

RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)?/?$ index.php?page=$1&cat=$2&sub=$3 [NC,L]
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ index.php?page=$1&cat=$2 [NC,L]

My issue is that when I try to $_GET the category, it doesn't work when there's only a category and not a subcategory

sitename/order/meat/beef

Here I can $_GET the category(meat)

sitename/order/meat

And here I can't

I'm fairly green in the htaccess department, and googling hasn't born any fruit.

What do?

Upvotes: 0

Views: 1296

Answers (1)

Rich Bowen
Rich Bowen

Reputation: 5892

Your regex makes all portions of the match mandatory rather than optional so if any are missing the entire thing fails.

Two suggested solutions,

1) replace the RewriteRule solution with

FallbackResource /index.php

And then use explode() in php to get the arguments. This is by far the most efficient solution. That is, in your php, you'd do:

list($page, $cat, $sub) = explode('/', trim($_SERVER['PATH_INFO'], '/') ); 

2) Ok, let's try a different approach:

So, to update the entire ruleset:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# page
RewriteRule ^([^/]+)/?$  index.php?page=$1 [NC,L]

# page/category
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?page=$1&cat=$2 [NC,L]

# page/category/sub
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ index.php?page=$1&cat=$2&sub=$3 [NC,L]

Upvotes: 1

Related Questions