Serve static content from a cookieless domain in NGINX

Very simple one to help anyone out there fix the issue regarding serving static content from a cookieless domain in NGINX. This does not require a CDN or sub domain, etc like most tutorials.

It’s simply a few lines of code to add to your host file:

location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js|scss|map|less|woff|woff2|otf|eot|ttf)$ {
   expires     max;
   fastcgi_hide_header "Set-Cookie";
}

A real example

server {
    listen      185.122.57.134:443 ssl http2;
    server_name blog.ss88.us www.blog.ss88.us;
    root        /XXX/XXX/XXX/public_html;
    index       index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;

        location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js|scss|map|less|woff|woff2|otf|eot|ttf)$ {
            expires     max;
            fastcgi_hide_header "Set-Cookie";
        }
}

 

Note: if you use Cloudflare, this will not work.

6 thoughts...

  1. Indospace.io says:

    need to add more file extensions..
    scss|map|woff| …

    1. I’ve updated some more! Ty 🙂

      1. Indospace.io says:

        I can guarantee this works now. Anyone having difficulty to this prior were most likely using tools such as tools.pingdom.com to verify results. These tools will fail if just one file comes back with a cookie, everyone has a different use case. For example, if you are retrieving a JSON object from static you’ll need to add |json| etc… There are so many of them, it is up to you as a developer to determine which static objects you’re retrieving and loading any potential missing extensions.

  2. Dan Denkijin says:

    This doesn’t work for me.

    1. Nick Mason says:

      Yeah, wish it were this easy, but fastcgi_hide_header is a server-level directive per the nginx docs, NOT a location-level directive.

Leave a Reply

Your email address will not be published. Required fields are marked *

 

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>