1

I want to make my website to have 'pretty-urls'. Also I want to make so users which input 'ugly' urls will be redirected to 'pretty-urls'.

Simplified example:
I have page data.php?id=123. I want so it shows to users as data/123 and for whose who typed in address bar data.php?id=123 it will be redirected to data/123.

I have tried following code in .htaccess:

# redirect to pretty url
RewriteCond %{QUERY_STRING} ^id=([0-9]+)$
RewriteRule ^/?data\.php data/%1? [R=301,L]

# convert pretty url to normal
RewriteRule ^/?data/([0-9]+)$ data.php?id=$1 [L]

However it doesn't work, it goes into infinite loop as I understood.

Is what I wanted possible and how if yes?

Somnium
  • 1,059
  • 1
  • 9
  • 34

1 Answers1

2

Using %{QUERY_STRING} for your case will produce a infinite loop because the internal destination also relies on it.

However using %{THE_REQUEST} does not:

# Redirect /data.php?id=123 to /data/123
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+data\.php\?id=([0-9]+) [NC]
RewriteRule ^ /data/%1? [R=302,L]

# Internally forward /data/123 to /data.php?id=123
RewriteRule ^data/([0-9]+)/?$ /data.php?id=$1 [NC,L]
Prix
  • 19,417
  • 15
  • 73
  • 132
  • Thank you! It works! However I don't understand `[A-Z]{3,}\s/+` part what is for. – Somnium Feb 20 '15 at 08:30
  • that relates to the method being used for example POST, GET, etc – Prix Feb 20 '15 at 08:37
  • Thanks. However I have realized that new problem arose. PHP's working path changes to /data/ and for that reason links to all resources (images, css) are broken (links are relative, changing to absolute helps, but I need to preserve relative paths). Can this be fixed without changing links in website pages? – Somnium Feb 20 '15 at 08:46
  • 1
    [Use the **`base`** tag to resolve that](http://www.w3.org/TR/html4/struct/links.html#h-12.4) or a much simpler solution, use the right links in your code rather than having to work around it with regex :) – Prix Feb 20 '15 at 09:01