How to add file type extension using .htaccess?

孤街醉人 提交于 2019-12-11 12:23:13

问题


I want to map links like http://example.com/STRING to http://example.com/STRING.png, how to do it with .htaccess?


回答1:


Try the following code in htaccess :

RewriteEngine on


RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.png -f

RewriteRule ^([^/]+)/?$ /$1.png [NC,L]



回答2:


Try:

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/(.*)$
RewriteCond %{DOCUMENT_ROOT}/%1.png -f
RewriteRule ^(.*)$ /%1.png [L]



回答3:


This one should, theoretically (I haven't tested it), redirect to first file in directory which is made of the given string (http://example.com/STRING) and 1 to 4 letters/numbers extension.

For example, these are your files:

.htaccess
file.php
img.jpg
anotherimg.gif
doc.html

if you request example.com/doc it will redirect you to example.com/doc.html example.com/anotherimg redirects to example.com/anotherimg.gif

.htaccess:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([a-zA-Z0-9]*)$ file.php?name=$1 [L]

file.php:

$files = scandir('./');

foreach($files as $file)
{
    if (preg_match(
        '/^'. $_GET['name'] .'.[a-zA-Z0-9]{1,4}/',
        $file
    )) {
        header("Location: $file");
        break;

    } else continue;

}


来源:https://stackoverflow.com/questions/33984812/how-to-add-file-type-extension-using-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!