Rewrite URL term(s) separated by equal sign to query string(s)

By : kiteman

Using mod_rewrite, what RewriteRule(s) would make the following two examples function properly?

Example #1 (one term):

Example #2 (two terms):

Note: The .htaccess file is located in /dir/ outside of domain root.

I've gotten close with this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)=([^/]*)/?$ index.php?a=$1&b=$2 [L]

However, to work with example #1 a trailing "=" is required (which I want to avoid). I've tried changing "=" to "=?" in the regex to make it optional but while it then works for example #1 it fails for example #2.

Thank you kindly for any consideration to my question. I'm new to mod_rewrite and regex and am truly stumped.

By : kiteman


Why not create two seperate rewrite rules:

i) One that takes care of example 1 - with the added check that it does not contain an equal sign [so that you don't match example 2 with rewrite rule 1]

ii) Another one that takes care of example 2

By : related

I see two main approaches:

1. More safer/easier to understand and extend if necessary. Make two rules: 1st will catch thanks=stackoverflow while 2nd will work with thanks only:

RewriteEngine On

# do not do anything for already existing files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]

# will work with /thanks=stackoverflow
RewriteRule ^([^/=]+)=([^/=]+)/?$ index.php?a=$1&b=$2 [L]
# will work with /thanks
RewriteRule ^([^/=]+)/?$ index.php?a=$1 [L]

2. Combine those two rules into a single rule. In this case parameter b= will always be present, but will be empty for thanks scenario:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/=]+)(=([^/=]+))?/?$ index.php?a=$1&b=$3 [L]

Tested both -- working fine on my Apache box.

By : LazyOne

This video can help you solving your question :)
By: admin