If someone goes to example.com/video.mov and that's the wrong extension, what code can I add to .htaccess to have it auto-correct it to the correct file which would be example.com/video.mp4?
CodePudding user response:
The principle is very similar to "extensionless files" as outlined in my answer to your previous question, except that you need to check whether the requested file exists first. You may also need to force the appropriate mime-type for the new resource.
For example, if a request for <anything>.mov does not exist then internally rewrite the request to <anything>.mp4 instead if that file exists, otherwise defaults to a 404.
RewriteEngine On
# Rewrite request from .mov to .mp4 on failure
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.mp4 -f
RewriteRule (. )\.mov$ $1.mp4 [T=video/mp4,L]
The above does the following in order:
(. )\.mov$- TheRewriteRulepattern checks that the request ends in.mov- The first condition (
RewriteConddirective) checks that the request does not map to a file. - The second condition checks that the corresponding
.mp4file does exist. - If the above checks are all satisfied the request is rewritten to the corresponding
.mp4file.
TheTflag sets the appropriateContent-Typeheader on the response.
