Using .htaccess to change what URL is being displayed, but without actually redirecting the content?

StackOverflow https://stackoverflow.com/questions/11402153

Question

I have a RewriteRule setup to change

http://kn3rdmeister.com/blog/post.php?y=2012&m=07&d=04&id=4

into

http://kn3rdmeister.com/blog/2012/07/04/4.php

but that actually redirects where the browser is getting the page from. I want to still display

/blog/post.php?y=xxxx&m=xx&d=xx&id=xx

but have the browser show the simpler URL like

/blog/post/year/month/day/id.php

I read something somewhere about using ProxyPass, but I don't quite know what I'm doing :P

I want people to be able to visit either the post.php URL with the query strings, OR the clean URL with fancy shmancy subdirectories for the dates and get the same content — all while displaying the clean URL in the end.

Was it helpful?

Solution

You want something like this:

# First if someone actually requests a /blog/post.php URL, redirect them
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD)\ /blog/post\.php\?y=([0-9]{4})&m=([0-9]{2})&d=([0-9]{2})&id=([0-9]*)\ HTTP/
RewriteRule ^blog/post\.php$ /blog/%2/%3/%4/%5.php [R=301,L]

This will redirect the browser to the /blog/##/##/##/##.php URI, that will show up in their address bar. Once they get redirected, the browser will then send a request for /blog/##/##/##/##.php and your server then needs to internally rewrite it back:

# We got pretty URLs, but need to rewrite back to the php request
RewriteRule ^blog/([0-9]{4})/([0-9]{2})/([0-9]{2})/([^\.]+)\.php$ /blog/post.php?y=$1&m=$2&d=$3&id=$4 [L]

This changes everything back internally so that the file /blog/post.php can handle the request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top