How to set .htaccess in React app (create-react-app) to display images

Viewed 664

Can anyone advise me how to set up .htaccess in me React app (create-react-app) to display images from a URL. My settings .htaccess

SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

RewriteRule ^files/(.*)$ /files/files.php?url=$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^ index.html [QSA,L]

I have the code

<img src="/files/2k28WHrMCJu9jSEEss0Y9sKV7Oqf4b/0/120" alt="" />

and i need it to convert to

<img src="/files/files.php?url=2k28WHrMCJu9jSEEss0Y9sKV7Oqf4b/0/120" alt="" />

I testing by entering a URL that should display the image directly in the browser "localhost:3000/files/2k28WHrMCJu9jSEEss0Y9sKV7Oqf4b/0/120". Instead of the image, the application page Not found (set in the react-router) is loaded.

1 Answers

Your code is littered with erroneous spaces - some will cause the 500 Internal Server Error and others that will prevent it from working as intended. Since you have so many erroneous spaces, it looks like you may have a problem with your "code" editor?!

Spaces are argument delimiters in Apache config files, so the arguments themselves must not contain spaces. (Aside: If arguments contain spaces then the space must be backslash-escaped or surround the whole argument in double quotes - although this is not the issue here.)

SetEnvIf Authorization. + HTTP_AUTHORIZATION=$0

The regex (2nd argument) should be .+, but you've mangled the arguments.

RewriteRule ^files/(.*)$ /files/files.php?url=$1 [L, QSA]

There should be no space in the flags argument. This will result in a 500 Internal Server Error and "bad flags delimiters" would be reported in the server logs.

This applies to both your RewriteRule directives.

However, once the syntax is corrected, this rule will also result in a rewrite-loop (another 500 error) because the RewriteRule pattern also matches the target URL. Since the URL-path you are trying to match does not appear to contain dots then you could simply exclude dots from the regex. ie. [^.]* instead of .*, to avoid matching files.php (which naturally contains a dot).

RewriteCond% {REQUEST_FILENAME}! -f

You have separated the first argument with a space. It should be % {REQUEST_FILENAME}. And again with the second argument, it should be !-f.

So, it should look like this instead:

SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

RewriteRule ^files/([^.]*)$ /files/files.php?url=$1 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.html [L]

The QSA flag was not required on the last rule.

NB: A 500 Internal Server Error is just a generic server response when there is a fatal error. You should check your server's error log for the details of this error.

Related