Forum Moderators: phranque

Message Too Old, No Replies

Rewrite portion of URL

rewrite portion

         

brite

6:11 pm on Aug 31, 2009 (gmt 0)

10+ Year Member



Hi,

New to rewriting and hoping for a some help. I'm trying to rewrite only a portion of a url which is in the middle. The rule I have constructed doesn't work properly. Here is what I'm trying to do:

Goal:

Rewrite Original: [mydomain.com...]

To: [mydomain.com[b]...]

My Rule:
RewriteRule ^example1/example2/$ /rewritten/ [R,L]

The rewrite doesn't work if there is anything in the URL after /example2/. Seems I'm missing a wild card of some type?

Thank you in advance

jdMorgan

6:26 pm on Aug 31, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You are missing a wild-card sub-pattern and a back-reference to the matched contents of that sub-pattern.

By 'capturing' the URL-path-part that follows /example2 and 'back-referencing' it in the substitution URL, you are in effect 'copying' it into the new URL.

To capture matched contents use parentheses to enclose the sub-pattern. To back-reference contents captured in RewriteRule, use $1 through $9, where the number corresponds to the number of left parentheses surrounding the contents that you want. To back-reference RewriteCond matches, use %1 through %9.

See the Apache mod_rewrite documentation for more details.


RewriteRule ^example1/example2/(.*)$ http://www.example.com/[i]rewritten[/i]/$1 [R=301,L]

Note that as shown above, I strongly suggest the use of a canonical URL in the substitution, in order to avoid problems if your server has "UseCanonicalName On" but your host has declared the 'wrong' canonical domain in the configuration file -- e.g. you prefer to use "www.example.com" but the ServerName is declared as "example.com" (or vice-versa).

Jim

brite

6:49 pm on Aug 31, 2009 (gmt 0)

10+ Year Member



Thank you kindly for the help and extremely informative reply Jim!