TJB
TJB

Reputation: 3846

Can't set expire header on images with Apache

I am trying to tell browsers to cache any type of image files (png/jpg/gif/etc) from my application, by setting up an .htaccess file in the root of my Django application.

.htaccess

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType image/gif "access plus 365 days"
  ExpiresByType image/jpeg "access plus 365 days"
  ExpiresByType image/png "access plus 365 days"
</IfModule>

Apache

LoadModule authz_core_module modules/mod_authz_core.so
LoadModule dir_module        modules/mod_dir.so
LoadModule env_module        modules/mod_env.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule mime_module       modules/mod_mime.so
LoadModule rewrite_module    modules/mod_rewrite.so
LoadModule setenvif_module   modules/mod_setenvif.so
LoadModule wsgi_module       modules/mod_wsgi.so
LoadModule unixd_module      modules/mod_unixd.so
LoadModule expires_module    modules/mod_expires.so
LoadModule headers_module    modules/mod_headers.so

<Directory />s
    AllowOverride All
</Directory>

LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog /home/timbaney1989/logs/user/access_baneydev.log combined
ErrorLog /home/timbaney1989/logs/user/error_baneydev.log

Before adding the AllowOverride All option, I was getting an internal server error, but now my app is running fine. When I check the network however and see images being loaded, I don't see the expire header anywhere on that image. Also the server says it is Nginx ? Is this a normal thing to be running your application on an Apache serve, and have an Nginx server loading your static files ? Is there somewhere in my Django application or Apache httpd.conf file that I am missing, or have entered incorrectly ?

enter image description here

Upvotes: 1

Views: 590

Answers (2)

Zach
Zach

Reputation: 566

You could also follow this guide for uWSGI and NGINX to replace apache, and set up static files as an alias in a location block instead, and add the headers from my previous answer.

http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html

Upvotes: 0

Zach
Zach

Reputation: 566

It looks the twitter.png file gets a 404:

HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html
Date: Sun, 06 Nov 2016 06:44:39 GMT
Server: nginx
Vary: Accept-Encoding

Here's a modified version of the solution by Nicholas Kuechler

location ~* \.(png|jpe?g|gif|ico|tiff)$ {
  expires max;
  log_not_found off;
  access_log off;
}

If it's getting 404, you likely have the root directive incorrectly setup for location-block inheritance. Confirm that the root (DocumentRoot) is correct, and that the file exists relative to the root path, and it should show.

Upvotes: 2

Related Questions