简体   繁体   中英

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?

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]

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