I am trying to use htaccess Rewrite Rules to map multiple GET variables, but not all the variables are required. I have ordered the variables so that x is always required, if y is set, then z must be set, etc. So I need the mappings to look like this:
example.com/section/topic/sub
to map to
example.com/?x=section&z=topic&y=sub
However the following code causes Internal Error, but if I only have 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 ensure the url can have a trailing /, but does not require it.
As you can probably tell, I am new to htaccess.
Thank You
RewriteCond %{REQUEST_URI} ([^/]+)/?
is doing./?$
You can have your rules like this in 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With