Search code examples
.htaccesspretty-urls

Redirect to 'pretty-urls' doesn't work


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?


Solution

  • 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]