Home > Back-end >  Auto correct file extensions with .htaccess
Auto correct file extensions with .htaccess

Time:10-29

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:

  1. (. )\.mov$ - The RewriteRule pattern checks that the request ends in .mov
  2. The first condition (RewriteCond directive) checks that the request does not map to a file.
  3. The second condition checks that the corresponding .mp4 file does exist.
  4. If the above checks are all satisfied the request is rewritten to the corresponding .mp4 file.
    The T flag sets the appropriate Content-Type header on the response.
  • Related