0

I want all mp3 files residing on my server to have "-xxx" added at the end of the filename when a user downloads them. Example:

file on the server: file.mp3

when user downloads: file-xxx.mp3

I've googled something that is pretty close to what I want:

https://forums.digitalpoint.com/threads/htaccess-rename-mp3.128317/

As I don't want to be limited to any particular folder, and would like to have all .mp3's renamed on the fly, I've tried this:

RewriteEngine on
RewriteBase /
RewriteRule ([^.]+)-by-domain\.mp3$ $1.mp3 [L]

but for some reason I can't get it to work, files don't get renamed.

Any help would be appreciated. Thanks!

1
  • RewriteRules don't "rename" files, they edit instead edit the request so the file being served can be found. So, the client won't be accessing file.mp3, the client will be accessing file-xxx.mp3, and the RewriteRule will simply allow the file named file.mp3 to be returned as the requested filename.
    – NReilingh
    Jan 31, 2013 at 15:46

1 Answer 1

0

The following worked when tested on my server

RewriteEngine on
RewriteBase /
RewriteRule ^/(.*)-([0-9]+).mp3 /$1.mp3

It works as follows - The RewriteRule is broken up into 4 parts,

  1. the prefix including the path and first part of the name of the file
  2. the "-"
  3. the numbers in the file
  4. the end part of the file (.mp3)

The script takes only the prefix from the original file - the part ^/(.*) and then rebuilds this into a new url (the $1 contains the part between the brackets in the part above).

The ([0-9]+) detects the unique number, so if you are wanting to do something more fancy later on you could write (for example) a PHP script which allows the user to download the file, and logs information about it by changing the rewrite rule to

RewriteRule ^/(.*)-([0-9]+).mp3 /path/process.php?mp3=$1&userid=$2

(You would need to write the php script as well of-course, but the example above shows the logic as to how the rewrite rule processes the URL into parts.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .