tfrancois tfrancois - 1 month ago 14
Apache Configuration Question

Apache mod-rewrite htaccess - dynamic url with parameters

fellow programmers!

I'm trying to get the following dynamic url:

http://example.com/pdfs/viewpdf?id=1494


To be rewritten in the browser's address bar:

http://example.com/pdfs/1494/1494.pdf


Basically, the user is entering in a request to view a PDF that is available on the file/web server and based on the ID number provided, the URL is rewritten to go and retrieve the document from a sub-folder under DOCUMENT_ROOT/pdfs/ whose folder name matches the ID provided along with the PDF filename matching the same ID. Can anyone help? Everything I've tried does not work.

Thanks in advance!

Answer

Try the following rule in root/.htaccess:

RewriteEngine on
#1 Iteration)Redirect "/pdfs/viewpdf/?id=123" to "/pdfs/123/123.pdf"
RewriteCond %{THE_REQUEST} /pdfs/viewpdf/?\?id=([^&\s]+) [NC]
RewriteRule ^ /pdfs/%1/%1.pdf? [L,R]
#2 iteration) internally map "/pdfs/123/123.pdf" to "/pdfs/viewpdf/?id=123"
RewriteRule ^pdfs/[^/]+/([^.]+)\.pdf$ /pdfs/viewpdf/?id=$1 [L,QSA]
Comments