Mobile app version of vmapp.org
Login or Join
Annie201

: Redirecting "ugly" urls to pretty ones? For example to display /id/123 for /urlugly?id=123 I can do RewriteRule ^id/([^/]*)$ /urlugly?id= [L] and apparently for redirect I can add [R] RewriteRule

@Annie201

Posted in: #Apache #Apache2 #Htaccess

For example to display /id/123 for /urlugly?id=123 I can do

RewriteRule ^id/([^/]*)$ /urlugly?id= [L]


and apparently for redirect I can add [R]

RewriteRule ^id/([^/]*)$ /urlugly?id= [R,L]


which redirects /id/123 to /urlugly?id=123 as expected.

if I wanted to redirect /urlugly?id=123 to /id/123 I thought

RewriteRule ^urlugly?id=$ /id/([^/]*) [R]
RewriteRule ^id/([^/]*)$ /urlugly?id= [L]


This would work... and I have tried some other similiar things, and I think my logic here is correct, but its obviously not.

So How do I redirect /urlugly?id=123 to /id/123? I can't seem to get it to work. I know (think?) [L] means "ignore others that match this" and I think it applies to the ones that are -below- that line with [L]

i.e. if I put [R] above that it would still work and [L] would also work... Is this correct?

What am I doing wrong here and what is the correct approach?

10.01% popularity Vote Up Vote Down


Login to follow query

More posts by @Annie201

1 Comments

Sorted by latest first Latest Oldest Best

 

@BetL925

It is difficult to rewrite your pretty URLs to a handler while at the same time redirecting ugly URLs for the handler back to the pretty URL. I had to ask how to do it at StackOverflow.

mod_rewrite makes multiple passes over your rules, so specifying the [L] flag is not enough. When you rewrite your pretty URL your need to set an environment variable. Then when you decide whether to redirect an ugly URL, only do so when the environment variable is not set (so that you avoid redirecting when it is only ugly because of your rewrite.) On the second pass when this redirect is evaluated, environment variables are all prefixed with REDIRECT_. So if you set a LOOP environment variable, you have to read it as REDIRECT_LOOP. Here is what should work for you:

RewriteEngine On

RewriteRule ^id/([^/]*)$ /urlugly?id= [L,E=LOOP:1]

RewriteCond %{ENV:REDIRECT_LOOP} !1
RewriteCond %{QUERY_STRING} id=(.+)
RewriteRule ^urlugly$ /id/%1 [R,L]

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme