I've been trying to get an .htaccess RewriteRule working for the past few days with no success. On the server I am working from, there is a website which allows uploads. The uploads are stored in folders located in a series of directories such as /content/uploads/photos/2023/04/<filename>
. An example filename would be: upl_35fbde0e97c7be3b8d8c684f538adf0a.jpg
The content directory is located at the same level of the filesystem as the .htaccess file I am editing.
Instead of serving the file directly, I want to load a PHP file (files.php?file=<filename>
) which determines if the user is logged in, prior to serving the file. This should be simple and I was able to get this working easily on another server in a simplified test environment I stood up.
The RewriteRule I created is RewriteRule ^content/uploads/(.*)$ files.php?file=$1 [L,QSA]
. I would expect it to redirect the above URL to /files.php?file=photos/2023/04/upl_35fbde0e97c7be3b8d8c684f538adf0a.jpg
, however no redirect occurs.
If I load the URL /content/uploads/photos/2023/04/upl_35fbde0e97c7be3b8d8c684f538adf0a.jpg
the file gets served, but not from files.php
(therefore, unauthenticated users can access). If I simply chop off the trailing 'g' in the filename so it does not match an existing file, it does load the files.php
script (EX: upl_35fbde0e97c7be3b8d8c684f538adf0a.jp
).
I'm a bit at a loss as to why this is happening, as I've tried many different configurations in my .htaccess file, including removing everything else except this redirect rule - but to no avail. Any suggestions or pointers would be greatly appreciated.
It looks like you are perhaps behind a front-end proxy that is serving your static assets (Nginx is often used for this). This is in the interests of "performance". If this is the case then Apache/.htaccess
is bypassed entirely for static file requests. You would need to configure the proxy to allow these requests through. Check the HTTP response headers (particularly the Server
header) for clues as to where the response is being served from.
Otherwise, the mod_rewrite rule you've posted would seem to be OK, providing it is placed at the top of the .htaccess
file and files.php
is also located at the same level as the content
subdirectory.