Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally set headers in Apache htaccess

I have a PHP Laravel application with a standard .htaccess file as follows.

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

If the requested URL maps to a static file, it is served, and otherwise index.php is invoked. I need to add a set of headers for static files, which would kind of be the "else" of the last two conditions above. I need something like the below pseudo.

if static file
    Header set MyHeaderOne "something"
    Header set MyHeaderTwo "something"
end if

I can add the headers just fine, but got stuck at doing so conditionally. I looked a bit at SetEnvIf, which may make it possible.

So, how can I add some headers only for static files, i.e. if the requested file exists (e.g. /images/example.jpg)? Thanks a lot in advance!

like image 630
ba0708 Avatar asked Feb 07 '23 09:02

ba0708


1 Answers

You can do a condition statement just like what you stated.

<If "%{REQUEST_URI} =~ /\.(gif|jpe?g|png|css|js)$/">
  #put your header set stuff here
</If>

https://httpd.apache.org/docs/2.4/expr.html#examples

like image 176
Panama Jack Avatar answered Feb 16 '23 20:02

Panama Jack