Robert Strauch
Robert Strauch

Reputation: 12896

Rewriting URLs with mod_rewrite for languages

I need some URL rewriting for my website using mod_rewrite but I can't figure out the regular expressions.

Here is what the current URLs may look like:
http://mydomain.com/zenphoto/pages/xyz?locale=en_US
http://mydomain.com/zenphoto/pages/xyz?locale=de_DE

http://mydomain.com/zenphoto/gallery_1?locale=de_DE
http://mydomain.com/zenphoto/gallery_n?locale=de_DE

xyz may contain different strings, e.g. legal, about, etc.

And that's how I'd like the URLs to be used:
http://mydomain.com/zenphoto/de/pages/xyz
http://mydomain.com/zenphoto/en/pages/xyz

http://mydomain.com/zenphoto/de/gallery_1
http://mydomain.com/zenphoto/en/gallery_n

I should mention that only de and en shall be possible. Any other strings shall be rerouted to de.

Could somebody help me please? :-)

Thanks,
Robert

Upvotes: 1

Views: 443

Answers (1)

bfontaine
bfontaine

Reputation: 19835

RewriteEngine on
RewriteRule ^zenphoto/pages/([a-z]+)\?locale=(en|de)_[A-Z]{2}$ /zenphoto/$2/pages/$1
RewriteRule ^zenphoto/gallery_([0-9])\?locale=(en|de)_[A-Z]{2}$ /zenphoto/$2/gallery_$1

For the first example, I say: "If the URL starts (^) with "zenphoto/pages/" then have a sequence of lowercase letters (+ means "one or more", and [a-z] means "a letter in [a, b, ..., y, z]"), which is my first group (there is parentheses -> it's a group). Then it's followed by "?locale=", then by "en" or (| means "or") "de", and this is my second group, then it's followed by an underscore ("_") and two uppercase letters, and there is nothing after ($ means it's the end of the URL)". I write a space, and the new URL I want, and I use $n to use the n-th group. The second URL is the 'pretty one', and the first is the real.

You have to use backslashes before special chars like ?,+,{,},(,),[,],*,.,| if you want to use one in your URL.

Edit:

If you want to avoid infinite loops, you should add the flag [L] (L = Last) at the end of each line.

Upvotes: 3

Related Questions