简体   繁体   中英

Rewrite PHP Query URL to Image with .htaccess Mod Rewrite Rule

How can I rewrite a PHP query url to an actual image?

I'd like http://localhost/img.php?image=winter.jpg to be rewritten to http://localhost/img/winter.jpg The image name changes dynamically.

I tried like this but it doesn't work.

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.+img\.php\?.*?image\=(.+)[$&] ./img/$1 [NC]

Thanks.

[Update]

After accessing http://localhost/img.php?image=winter.jpg the following text was appended to the log file. The browser shows the message, "Object Not Found! The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again."

127.0.0.1 - - [<time>] [localhost/sid#975148][rid#4d09cb8/initial] (3) [perdir Z:/xampp/htdocs/] strip per-dir prefix: Z:/xampp/htdocs/img.php -> img.php
127.0.0.1 - - [<time>] [localhost/sid#975148][rid#4d09cb8/initial] (3) [perdir Z:/xampp/htdocs/] applying pattern '^.+img\.php\?.*?image=(.+)[$&]' to uri 'img.php'
127.0.0.1 - - [<time>] [localhost/sid#975148][rid#4d09cb8/initial] (3) [perdir Z:/xampp/htdocs/] pass through Z:/xampp/htdocs/img.php

[Update]

The error logs says,

[<time>] [error] [client 127.0.0.1] script 'Z:/xampp/htdocs/img.php' not found or unable to stat

So I created a dummy file named img.php and the error stated not being shown any more. I've assumed that a dummy file was not necessary. Now it only displays the contents of the dummy PHP file when I access http://localhost/img.php?image=winter.jpg

I tried [NC,L] , [R,NC] , [R,NC,L] but none of them worked.

This should work. The browser may need to be restarted.

RewriteEngine on
RewriteCond %{QUERY_STRING} ^image=(.*)$
RewriteRule ^.*img\.php$ ./img/%1 [NC,QSA]

Related: mod rewrite Rule for Image + String to Imagefolder Rewrite

You are not redirecting. Add the Redirect flag, try [R] at the end:

RewriteRule ^.+img\.php\?.*?image\=(.+)[$&] ./img/$1 [R,NC]
                                                      ^ 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM