Htaccess multiple rewrite rules for different GET variables

I am trying to use htaccess Rewrite Rules to map multiple GET variables, but not all variables are required. I ordered the variables so that x is always required, if y is given, then z must be set, etc. Therefore, I need the mappings to look like this:

example.com/section/topic/sub

to display on

example.com/?x=section&z=topic&y=sub

However, the following code causes an internal error, but if I have only one Rewrite rule, it works.

Options +FollowSymLinks
Options -indexes
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI}  ([^/]+)/?   [NC]
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)$  ?x=$1&z=$2&y=$3&r=$4    [NC,L]
RewriteRule ^([^/]+)/([^/]+)/([^/]+)$  ?x=$1&z=$2&y=$3    [NC,L]
RewriteRule ^([^/]+)/([^/]+)$  ?x=$1&z=$2    [NC,L]
RewriteRule ^([^/]+)$  ?x=$1    [NC,L]

</IfModule>

I also need to make sure that the url can have trailing /, but does not require it.

As you probably can tell, I'm new to htaccess.

thanks

+4
source share
2 answers
  • , RewriteCond %{REQUEST_URI} ([^/]+)/?.
  • - /?$
  • / .

DOCUMENT_ROOT/.htaccess:

Options +FollowSymLinks -indexes
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /

## If the request is for a valid directory
RewriteCond %{REQUEST_FILENAME} -d [OR]
## If the request is for a valid file
RewriteCond %{REQUEST_FILENAME} -f [OR]
## If the request is for a valid link
RewriteCond %{REQUEST_FILENAME} -l
## don't do anything
RewriteRule ^ - [L]


RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ ?x=$1&z=$2&y=$3&r=$4 [L,QSA]

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ ?x=$1&z=$2&y=$3 [L,QSA]

RewriteRule ^([^/]+)/([^/]+)/?$ ?x=$1&z=$2 [L,QSA]

RewriteRule ^([^/]+)/?$ ?x=$1 [L,QSA]

</IfModule>

: Apache mod_rewrite

+12

, , -, :

RewriteRule ^(.*)/*(.*)/*(.*)/*(.*)/*$ index.php?a=$1&b=$2&c=$3&d=$4

PHP - :

//var_dump($_GET);

array(4) {
  ["a"]=>
  string(#) "VALUE"
  ["b"]=>
  string(#) "VALUE"
  ["c"]=>
  string(#) "VALUE"
  ["d"]=>
  string(#) "VALUE"
}

VALUE , URL-, , .

N.B. , /; .

:

http://example.com/section/topic/sub

URL, , :

http://example.com/index.php?a=section&b=topic&c=sub&d=

PHP :

//var_dump($_GET);

array(4) {
  ["a"]=>
  string(7) "section"
  ["b"]=>
  string(5) "topic"
  ["c"]=>
  string(3) "sub"
  ["d"]=>
  string(0) ""
}
+2

All Articles