BrandonKlassen
BrandonKlassen

Reputation: 11

Need help writing URL Rewrite rule Regular Expression for PHP and htaccess

I've read a lot of sites talking about how to use Rewrite Rules and Regular Expressions, but they all tend to be for specific examples without breaking down every piece of the syntax and actually helping me to learn the concepts so that I can write the type of code I need.

Any help is much appreciated!

I have a url like this http://www.mysite.com/myphp.php?x=1A&y=2B&c=some1&d=some2

I would like this to rewrite like this: http://www.mysite.com/some1/some2

It seems really simple, but as I mentioned, I haven't run into a site explaining the concepts in a way that I could figure out how to make this work.

In this particular example, ?x= is always the same, while 1A varies. The same applies to each of the other pieces of the php string, however, I'm assuming the rewrite rule should handle any number of characters between the .php file and the variables I'm actually interested in.

Thanks again to anyone who can help explain this or provide a high quality resource on both rewrite rules and regular expressions to help me learn it.

Upvotes: 1

Views: 4561

Answers (2)

fred2
fred2

Reputation: 1110

Something like (not tested) added to .htaccess?

RewriteEngine on
RewriteRule ^/([0-9a-z]+)/([0-9a-z]+)/$ /?c=$1&d=$2 [L]

assuming x and y are not of interest.

Upvotes: 0

Ansari
Ansari

Reputation: 8218

A rule like this will work (tested):

RewriteRule ^([^/]+)/([^/]+) myphp.php?x=1A&y=2B&c=$1&d=$2 [L]

There are three parts to this:

  1. RewriteRule specifies that this is a rule for rewriting (as opposed to a condition or some other directive). The command is to rewrite part 2 into part 3.
  2. This part is a regex, and the rule will be run only if the URL matches this regex. In this case, we are saying - look for the beginning of the string, then a bunch of non-slash characters, then a slash, then another bunch of non-slash characters. The parentheses mean the parts within the parentheses will be stored for future reference.
  3. Finally, this part says to rewrite the given URL in this format. $1 and $2 refer to the parts that were captured and stored (backreferences)

As for high-quality resources on mod_rewrite, in the past I've found a few by searching for "mod_rewrite tutorial" (I thought this was a good one for a beginner). They'll mostly be like that, so if there's anything specific you don't understand, get that out of the way before moving forward. I'm not sure how else the syntax can be explained.

Regexes are a different thing, again, many resources out there - including for beginners. Once you get the basic hang of regexes, you can use the Python re page as a reference.

Upvotes: 3

Related Questions